解析XML与PHP的SimpleXML [英] Parsing XML with PHP's simpleXML

查看:142
本文介绍了解析XML与PHP的SimpleXML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习如何与PHP的简单的XML解析XML。我的code是:

I'm learning how to parse XML with PHP's simple XML. My code is:

<?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);
?>

在此运行它返回一​​个空白屏幕,没有任何错误。如果我删除所有从文档标签的属性,它返回:

When this runs it returns a blank screen, with no errors. If I remove all the attributes from the Document tag, it returns :

myApp SimpleXMLElement Object ( [0] => myApp )

这是预期的结果。

Which is the expected result.

我是什么做错了吗?请注意,我没有对XML源控制,因为它是从苹果来了。

What am I doing wrong? Note that I don't have control over the XML source, since it's coming from Apple.

推荐答案

有关默认命名空间的一部分,读<一个href=\"http://stackoverflow.com/questions/2386490/parsing-xml-with-phps-simplexml/2386706#2386706\">fireeyedboy's回答。正如mentionned,你需要的,如果你想对那些在默认命名空间节点使用XPath来注册一个名称空间。

For the part about the default namespace, read fireeyedboy's answer. As mentionned, you need to register a namespace if you want to use XPath on nodes that are in the default namespace.

不过,如果你不使用的XPath(),SimpleXML的都有自己的魔力,自动地选择默认的命名空间。

However, if you don't use xpath(), SimpleXML has its own magic that selects the default namespace automagically.

$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;
}

这篇关于解析XML与PHP的SimpleXML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆