[英]PHP cURL, extract an XML response
I am invoking PHP cURL method on a server and the response is XML type. 我在服务器上调用PHP cURL方法,响应为XML类型。 cURL is saving the output (after removing the tags) in a scalar type variable.
cURL将输出(在删除标记之后)保存在标量类型变量中。 Is there a way to store it in an object/hash/array so that it's easy to parse?
有没有一种方法可以将其存储在对象/哈希/数组中,以便于解析?
<?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";
}
Just add header('Content-type: application/xml');
只需添加
header('Content-type: application/xml');
before your echo of the XML response and you will see an XML page. 在回显XML响应之前,您将看到一个XML页面。
Example: 例:
<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>
then: 然后:
<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>
Output on your browser: Ship of Nomads 浏览器上的输出: 游牧民族之船
credits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5 积分: http : //blog.teamtreehouse.com/how-to-parse-xml-with-php5
$sXML = download_page('http://alanstorm.com/atom');
// Comment This
// $oXML = new SimpleXMLElement($sXML);
// foreach($oXML->entry as $oEntry){
// echo $oEntry->title . "\n";
// }
// Use json encode
$xml = simplexml_load_string($sXML);
$json = json_encode($xml);
$arr = json_decode($json,true);
print_r($arr);
no, CURL does not have anything with parsing XML, it does not know anything about the content returned. 不,CURL解析XML没有任何内容,它对返回的内容一无所知。 it serves as a proxy to get content.
它充当获取内容的代理。 it's up to you what to do with it.
由您决定如何处理。
use JSON if possible (and json_decode) - it's easier to work with, if not possible, use any XML library for parsin such as DOMXML: http://php.net/domxml 如果可能的话(和json_decode)使用JSON-如果可能的话,使用任何XML库进行解析都更容易,例如DOMXML: http ://php.net/domxml
simple load xml file .. 简单的加载xml文件..
$xml = @simplexml_load_string($retValuet);
$status = (string)$xml->Status;
$operator_trans_id = (string)$xml->OPID;
$trns_id = (string)$xml->TID;
?> ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.