【问题标题】:Can't get node's text with XPATH from my XML using PHP无法使用 PHP 从我的 XML 中获取带有 XPATH 的节点文本
【发布时间】:2018-07-04 09:01:08
【问题描述】:

大家好,感谢您抽出宝贵时间,我正在尝试解析一个大型 XML 文件(如下图)并使用 PHP 中的 XPATH 表达式获取特定节点的文本。

这是我的 php:

<?php
echo "[Generation Starts !]\n";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

error_reporting(E_ALL);



if (file_exists('../source/particuliers/arborescence.xml')) {


$xml = new SimpleXMLElement(file_get_contents('../source/particuliers/arborescence.xml'));

$xml->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/');

$themes = $xml->xpath("/Arborescence/Item[@type='Theme']/Titre/text()");

var_dump($themes);





$JSON = json_encode($themes, JSON_UNESCAPED_UNICODE);

file_put_contents('testing.json', $JSON);

echo "[Generation Done !]\n";

} else {

  echo "File wasn't found\n";

}

我不会把整个 XML 文件放在这里,因为它太大了,但这是一张图片,所以你可以看到结构

使用这个 XPATH 表达式 /Arborescence/Item[@type='Theme']/Titre/text() 我希望从我的节点中获取文本,但我只有一个空数组,其中包含正确数量的元素,但都是空的。

我做错了什么?

【问题讨论】:

  • 由于Item[@type='Theme'] 匹配许多项目,您很可能得到 NodeList (php.net/manual/en/class.domnodelist.php),而不是空数组 - 请检查返回的类型。在这种情况下,您需要遍历项目。如果您只想获取单个项目,请使用唯一的项目选择器,例如Item[@ID='19809'] 测试 XPath 是否真的有效。此外,您可能需要强制转换为 (string) 返回的结果,否则 XPath 可能会返回节点对象而不是值。
  • 非常感谢这个问题,我会好好检查一下,谢谢
  • 经过一个简单的过程确实可以: foreach ($themes as $key => $value) { echo (string)$value; } 我可以看到我的文字,抱歉新蜜蜂的问题:€

标签: php xml xpath


【解决方案1】:

SimpleXMLElement::xpath() 的结果始终是 SimpleXMLElement 对象的数组(或者对于无效表达式为 false)。 SimpleXMLElement 对象表示元素节点,但扩展对文本节点和属性有一些魔力。

将问题中的代码剥离为示例:

$xml = <<<'XML'
<Arborescence>
  <Item type="Theme">
    <Titre>Loisirs</Titre>
  </Item>
</Arborescence>
XML;

$xml = new SimpleXMLElement($xml);
$themes = $xml->xpath("/Arborescence/Item[@type='Theme']/Titre/text()");

var_dump($themes);

输出:

array(1) { 
  [0]=> 
  object(SimpleXMLElement)#2 (1) { 
    [0]=> 
    string(7) "Loisirs"
  }
}

结果是一个包含文本的具有单个 SimpleXMLElement 的数组。您可以使用array_map() 将所有返回的对象转换为字符串。

$xml = new SimpleXMLElement($xml);
$themes = array_map(
    function(SimpleXMLElement $element) {
        return (string)$element;
    },
    $xml->xpath("/Arborescence/Item[@type='Theme']/Titre/text()")
);

输出:

array(1) {
  [0]=> 
  string(7) "Loisirs" 
}

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 2014-01-14
    • 2015-03-08
    • 1970-01-01
    相关资源
    最近更新 更多