php - 我如何使用 php domdocument 导入同名的 xml 列表
问题描述
使用 php domdocument,导入 xml 文件,我不能有“标签”列表
我尝试了多种方法,但我不能
xml文件:
<resource>
<title>hello world</title>
<tags>
<resource>great</resource>
<resource>fun</resource>
<resource>omg</resource>
</resource>
php:
<?php
$url='test.xml';
$doc = new DOMDocument();
$doc->load($url);
$feed = $doc->getElementsByTagName("resource");
foreach($feed as $entry) {
echo $entry->getElementsByTagName("username")->item(0)->nodeValue;
echo '<br>';
echo $entry->getElementsByTagName("tags")->item(0)->nodeValue;
echo '<br>';
}
我希望输出是这样的列表:
你好,世界,
非常
有趣,
天哪
但实际输出不是列表,结果是一个没有空格的句子:hello world greatfunomg
解决方案
DOMDocument::getElementsByTagName()
返回具有指定名称的所有后代元素节点。DOMElement::$nodeValue
将返回元素节点的文本内容,包括其所有后代。
在您的情况下echo $entry->getElementsByTagName("tags")->item(0)->nodeValue
fetches all tags
,访问该列表的第一个节点并输出其文本内容。那就是greatfunomg
。
使用 DOM 方法来访问节点是冗长的,并且需要大量的代码,如果你想正确地做到这一点,需要很多条件。如果使用 Xpath 表达式会容易得多。允许您对来自 DOM 的节点的值和列表进行标量。
$xml = <<<'XML'
<_>
<resource>
<title>hello world</title>
<tags>
<resource>great</resource>
<resource>fun</resource>
<resource>omg</resource>
</tags>
</resource>
</_>
XML;
$document = new DOMDocument();
$document->loadXML($xml);
// create an Xpath instance for the document
$xpath = new DOMXpath($document);
// fetch resource nodes that are a direct children of the document element
$entries = $xpath->evaluate('/*/resource');
foreach($entries as $entry) {
// fetch the title node of the current entry as a string
echo $xpath->evaluate('string(title)', $entry), "\n";
// fetch resource nodes that are children of the tags node
// and map them into an array of strings
$tags = array_map(
function(\DOMElement $node) {
return $node->textContent;
},
iterator_to_array($xpath->evaluate('tags/resource', $entry))
);
echo implode(', ', $tags), "\n";
}
输出:
hello world
great, fun, omg
推荐阅读
- c++ - 在 C++ 中使用您自己的 Matrix 类进行 OpenGL 对象旋转
- wordpress - 如何将现有代码转换为 WooCommerce 插件
- javascript - 如何使用jquery验证网址
- google-places-api - 使用 google place API 获取一个国家所有驾驶学校的列表,但我只能使用 API 获得其中的 60 个,知道问题出在哪里吗?
- flask - 如何通过命令行 flask run 启动 Flask 和 Flask-SocketIO
- php - 在 PHP 中从配置文件中设置静态变量
- python - 将属性从一个类传递给另一个调用
- hyperledger-fabric - 错误 - 注册新身份时出现“路径长度约束的中间体过多”
- sapui5 - FilterBar 中的 BasicSearch 不起作用
- python - 断言:奇怪的比较结果 Python