使用 PHP 的 simpleXML 解析 XML [英] Parsing XML with PHP's simpleXML

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

问题描述

我正在学习如何使用 PHP 的简单 XML 解析 XML.我的代码是:

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

当它运行时,它返回一个空白屏幕,没有错误.如果我从 Document 标签中删除所有属性,它会返回:

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 )

这是预期的结果.

我做错了什么?请注意,我无法控制 XML 源代码,因为它来自 Apple.

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

推荐答案

关于默认命名空间的部分,请阅读 fireeyedboy 的回答.如前所述,如果要在默认命名空间中的节点上使用 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;
}

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

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