用PHP的simpleXML解析XML
问题描述:
我在学习如何用PHP的简单XML解析XML。我的代码是:用PHP的simpleXML解析XML
<?php
$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\"> <iTunes> myApp </iTunes> </Document>";
$xml = new SimpleXMLElement($xmlSource);
$results = $xml->xpath("/Document/iTunes");
foreach ($results as $result){
echo $result.PHP_EOL;
}
print_r($result);
?>
当这运行它返回一个空白屏幕,没有错误。如果我从文档标记中删除所有属性,则返回:
myApp SimpleXMLElement Object ([0] => myApp)
这是预期结果。
我在做什么错?请注意,我无法控制XML源,因为它来自Apple。
答
有关默认命名空间的部分,请阅读fireeyedboy's answer。如前所述,如果要在默认名称空间中的节点上使用XPath,则需要注册名称空间。
但是,如果您不使用xpath()
,SimpleXML有其自己的魔术可以自动选择默认名称空间。
$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?> <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\"> <iTunes> myApp </iTunes> </Document>";
$Document = new SimpleXMLElement($xmlSource);
foreach ($Document->iTunes as $iTunes)
{
echo $iTunes, PHP_EOL;
}
答
这条线:
print_r($result);
是foreach循环之外。也许你应该试试
print_r($results);
改为。
答
似乎如果你在xpath上使用通配符(//),它将起作用。此外,不知道为什么,但如果您从Document元素中删除名称空间属性(xmlns),您当前的代码将工作。也许是因为前缀没有定义?不管怎样,下面应该工作:
$results = $xml->xpath("//iTunes");
foreach ($results as $result){
echo $result.PHP_EOL;
}
答
你的XML包含默认命名空间。为了让你的xpath查询起作用,你需要注册这个命名空间,并且在你正在查询的每个xpath元素上使用命名空间前缀(只要这些元素都在同一个命名空间下,在你的例子中它们就是这样):
$xml = new SimpleXMLElement($xmlSource);
// register the namespace with some prefix, in this case 'a'
$xml->registerXPathNamespace('a', 'http://www.apple.com/itms/');
// then use this prefix 'a:' for every node you are querying
$results = $xml->xpath('/a:Document/a:iTunes');
foreach($results as $result)
{
echo $result . PHP_EOL;
}
答
这是一般的例子
foreach ($library->children() as $child)
{
echo $child->getName() . ":\n";
foreach ($child->attributes() as $attr)
{
echo $attr->getName() . ': ' . $attr . "\n";
}
foreach ($child->children() as $subchild)
{
echo $subchild->getName() . ': ' . $subchild . "\n";
}
echo "\n";
}
了解更多信息检查: http://www.yasha.co/XML/how-to-parse-xml-with-php-simplexml-DOM-Xpath/article-1.html
太棒了!你能指点我详细解释这个功能的文档吗? – SooDesuNe 2010-03-06 01:47:44
嗯,就是这样的事情:就我所知,没有关于如何处理默认名称空间的文档。 – 2010-03-06 16:37:19