PHP cURL,提取XML响应

时间:2009-02-18 16:25:13

标签: php curl

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

6 个答案:

答案 0 :(得分:111)

<?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";
}

答案 1 :(得分:8)

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

答案 2 :(得分:3)

示例:

<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>

然后:

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

浏览器输出:游牧民发货

信用:http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

答案 3 :(得分:3)

            System.out.println(System.getenv("MACHINE"));
            System.out.println(System.getenv("HOSTNAME"));

答案 4 :(得分:2)

不,CURL没有解析XML的任何内容,它对返回的内容一无所知。它作为获取内容的代理。这取决于你如何处理它。

如果可能的话,使用JSON(和json_decode) - 如果不可能的话,更容易使用任何XML库作为解析器,例如DOMXML: http://php.net/domxml

答案 5 :(得分:1)

简单加载xml文件..

$xml = @simplexml_load_string($retValuet);

$status = (string)$xml->Status; 
$operator_trans_id = (string)$xml->OPID;
$trns_id = (string)$xml->TID;

&GT;

相关问题