Soo*_*uNe 2 php itunes simplexml app-store
我正在学习如何使用PHP的简单XML解析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);
?>
Run Code Online (Sandbox Code Playgroud)
当它运行时,它返回一个空白屏幕,没有错误.如果我从Document标签中删除所有属性,它将返回:
myApp SimpleXMLElement Object ( [0] => myApp )
Run Code Online (Sandbox Code Playgroud)
这是预期的结果.
我究竟做错了什么?请注意,我无法控制XML源,因为它来自Apple.
您的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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3189 次 |
| 最近记录: |