PHP cURL,提取XML响应

Rak*_*esh 35 php curl

我在服务器上调用PHP cURL方法,响应是XML类型.cURL在标量类型变量中保存输出(在删除标记之后).有没有办法将它存储在一个对象/散列/数组中,以便它易于解析?

Ala*_*orm 113

<?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}
Run Code Online (Sandbox Code Playgroud)


小智 8

只需header('Content-type: application/xml');在回复XML响应之前添加,您将看到一个XML页面.


lim*_*ker 5

例子:

<songs>
<song dateplayed="2011-07-24 19:40:26">
    <title>I left my heart on Europa</title>
    <artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
    <title>Oh Ganymede</title>
    <artist>Beefachanga</artist>
</song>
<song dateplayed="2011-07-24 19:23:50">
    <title>Kallichore</title>
    <artist>Jewitt K. Sheppard</artist>
</song>
Run Code Online (Sandbox Code Playgroud)

然后:

<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>
Run Code Online (Sandbox Code Playgroud)

浏览器输出: 游牧之船

学分:http : //blog.teamtreehouse.com/how-to-parse-xml-with-php5