gpt4 book ai didi

php - 使用 PHP 的 simpleXML 解析 XML

转载 作者:行者123 更新时间:2023-12-03 01:39:21 24 4
gpt4 key购买 nike

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

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

myApp SimpleXMLElement Object ( [0] => myApp )

这是预期的结果。

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

最佳答案

您的 xml 包含默认命名空间。为了使您的 xpath 查询正常工作,您需要注册此 namespace ,并在您正在查询的每个 xpath 元素上使用 namespace 前缀(只要这些元素都属于同一 namespace ,就像您的示例中所做的那样):

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

关于php - 使用 PHP 的 simpleXML 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2386490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com