如何从URL

时间:2015-07-27 22:43:40

标签: php xml curl

我正在尝试从URL获取xml响应并使用类解析它,这非常简单。但这些是我得到的错误:

Notice: Trying to get property of non-object in /Applications/MAMP/...

如果我尝试使用

,这是我得到的错误
$xml = simplexml_load_file($url);

Warning: simplexml_load_file(): I/O warning : failed to load external entity
Warning: simplexml_load_file(url) failed to open stream: Cannot allocate memory in /Applications/MAMP/......

我尝试使用simplexml_load_string或simplexml_load_file的不同组合,有时它们可​​以工作,但大部分时间它们都在创建上面的错误。我也尝试过使用cURL,但仍然存在相同的错误,例如"试图在"中获取非对象的属性。但有时它能够获得xml响应并解析它。有谁知道如何解决这些错误。提前谢谢。

这是我的代码:

$ curl = curl_init();

curl_setopt_array($curl, Array(
    CURLOPT_URL            => $url,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_ENCODING       => 'UTF-8'
));

$getData = curl_exec($curl);
curl_close($curl);
print_r($getData);
// $xmlData = new SimpleXMLElement($getData);
$xml = simplexml_load_string($getData);
print_r($xml);
// // $xml = simplexml_load_file($getData);

$response = new ApiResponse($xml->{'status-code'}, $xml->{'status-code-description'}, $xml->{'data'});

1 个答案:

答案 0 :(得分:0)

下面的代码将显示示例API XML响应(url)中的所有数据。使用simplexml_load_file()将XML数据解释为对象。然后你可以使用它。

<?php

$html = "";

$url = "http://demo.cakemarketing.com/api/1/get.asmx/Advertisers?api_key=dNJFmId9rI";

$xml = simplexml_load_file($url);

for($i = 0; $i < count($xml);$i++){

      echo $xml->Advertiser[$i]->advertiser_name."<br/>";

}

?>

more details

此外,如果您收到Trying to get property of non-object错误,可能是您的XML数据不可用。如果您理解它,代码将使您理解:-D

相关问题