php获取xml数据

作者:matrix 发布时间:2013 年 10 月 27 日 分类:零零星星

调用某些api后返回的数据可能会是xml格式,这就需要提取相关数据。

如果了解正则匹配的话可以用preg_match()来提取,最好还是用php内置的专用函数来处理xml

 

代码:

$xml = new DOMDocument(); // 首先要建一个DOMDocument对象    
$xml->load('http://api.189.cn/EMP/shorturl/long2short?access_token=76327c4e405b725021640fd629bfc3511382853781284&app_id=120032470000032374&longurl=hhtjim.COM'); // 加载Xml文件     
$postDom = $xml->getElementsByTagName("shorturl")->item(0)->nodeValue;    
echo $postDom;  

 

说明:

第3行"shorturl"为读取的标签名,运行结果将显示http://189.io/ReRTnn

第2行是读取xml文件:


This XML file does not appear to have any style information associated with it. The document tree is shown below. <result> <res_code>0</res_code> <res_message>短地址生成成功。</res_message> <shorturl>http://189.io/ReRTnn</shorturl> </result>

参考:http://developer.51cto.com/art/200912/166247.htm


貌似这个代码也行

$xml = new DOMDocument();  
$xml->load('http://api.189.cn/EMP/shorturl/long2short?access_token=76327c4e405b725021640fd629bfc3511382853781284&app_id=120032470000032374&longurl=hhtjim.COM'); // 加载Xml文件     
foreach($xml->getElementsByTagName('shorturl') as $shorturl);
$value = $shorturl->firstChild->nodeValue;   
echo $value;