用PHP的simpleXML解析XML - php

我正在学习如何使用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);
?>

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

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

PHP-复选框组 - php

我有一个需要发布的表单复选框组。<input type="checkbox" value="true" checked name="chk0[]"> <input type="checkbox" value="false" name=…

PHP Count数组元素 - php

嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…

PHP:从函数返回值并直接回显它? - php

这可能是一个愚蠢的问题,但是……的PHPfunction get_info() { $something = "test"; return $something; } html<div class="test"><?php echo get_info(); ?></div> 有没有办…

PHP:将数据从二维数组复制到一维数组的最快方法 - php

我有一个巨大的二维PHP数组,带有500万行。$t = [ [ "id" => 1, "name" => "foo" ], [ "id" => 2, "name" => "bar" ] ]; 现在,我必须将此数组的I…

php-printf和sprintf具有不同的输出 - php

我编写了以下微型php程序来测试printf和sprintf:<?php $str_1 = printf("%x%x%x", 65, 127, 245); $str_2 = sprintf("%x%x%x", 65, 127, 245); echo $str_1 . "\n"; echo $s…