首页 > 解决方案 > 我如何使用 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

标签: phpxmlxml-parsingdomdocument

解决方案


DOMDocument::getElementsByTagName()返回具有指定名称的所有后代元素节点。DOMElement::$nodeValue将返回元素节点的文本内容,包括其所有后代。

在您的情况下echo $entry->getElementsByTagName("tags")->item(0)->nodeValuefetches 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

推荐阅读