我有以下代码:
<?php
$xmlString = '
<SHOP xmlns="http://www.example.com/ns/offer/1.0">
<SHOPITEM>
<ID>1</ID>
<PRODUCT>T-shirt</PRODUCT>
<PRICE>19,22</PRICE>
</SHOPITEM>
<SHOPITEM>
<ID>2</ID>
<PRODUCT>Trousers</PRODUCT>
<PRICE>87,54</PRICE>
</SHOPITEM>
</SHOP>';
$xml = simplexml_load_string($xmlString);
$x_s_products = $xml->xpath("/SHOP/SHOPITEM");
$cnt_x_products = count($x_s_products);
echo $cnt_x_products;
?>
问题在于$cnt_x_products
为0.但事实并非如此。如果我删除 xmlns属性,一切正常。但我必须有这个属性。谢谢你的建议。
答案 0 :(得分:2)
使用namespcae时,您必须register该命名空间:
$xml->registerXPathNamespace('n', 'http://www.example.com/ns/offer/1.0');
现在可行:
$x_s_products = $xml->xpath("//n:SHOPITEM");
$cnt_x_products = count($x_s_products);
echo $cnt_x_products;
输出2.