如何使用PHP解析XML中的单个条目?

时间:2012-02-03 06:41:13

标签: php xml

我正在尝试使用PHP从XML字符串中解析单个元素。问题是这个单独的元素在条目开始之前发生。 XML如下:

<?xml version="1.0" encoding="UTF-8"?>
<feed gd:kind="shopping#products"         gd:etag="&quot;lm_25heFT8yiumci9EH1kItJBpg/Sj5O9aXZ82PKpx3N2C3uQYMhNYE&quot;"     xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:s="http://www.google.com/shopping/api/schemas/2010">
 <openSearch:totalResults>64</openSearch:totalResults>
 <openSearch:startIndex>1</openSearch:startIndex>
 <openSearch:itemsPerPage>25</openSearch:itemsPerPage>
 <entry >...</entry>
 <entry >...</entry>
</feed>

我正在尝试解析opensearch:totalResults标记中的“64”。我如何将它分配给php中的变量?我试过了:

$url = 'url of xml feed'; 
$xml = simplexml_load_file($url); 
$entries =$xml->entry[0]->openSearch:totalResults;
      // also tried $entries =$xml->openSearch:totalResults;

echo $entries;

但它不起作用。有什么建议?

2 个答案:

答案 0 :(得分:1)

您需要注册名称空间才能访问这些节点:

$xml = simplexml_load_file('file.xml');
$xml->registerXPathNamespace('os', 'http://a9.com/-/spec/opensearchrss/1.0/');

$nodes = $xml->xpath('os:totalResults');
$totalResults = (string)$nodes[0];

答案 1 :(得分:0)

您也可以使用http://it1.php.net/manual/en/simplexmlelement.children.php(使用$ ns参数) 这是资源密集度较低的。