无法使用PHP从我的XML获取带有XPATH的节点文本

Hey everybody thanks for your time, I'm trying to parse a big XML file (pic bellow) and to get the text of specific nodes using XPATH expression in PHP.

Here is my php :

<?php
echo "[Generation Starts !]
";
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 !]
";

} else {

  echo "File wasn't found
";

}

I won't put the whole XML file here as it is way too big but here is a pic so you see the structure

xml file

Using this XPATH expression /Arborescence/Item[@type='Theme']/Titre/text() I expected to get text from my nodes but I only have an empty array with the right number of elements in it but all empty.

Anything I'm doing wrong ?

dongxuan1314
dongxuan1314 好吧,确实经过一个简单的:foreach($themesas$key=>$value){echo(string)$value;我可以看到我的文本,抱歉新问题:â€
大约 2 年之前 回复
duanliaoyin3171
duanliaoyin3171 非常感谢这一见解,我得对此进行正确的检查
大约 2 年之前 回复
douyuan9512
douyuan9512 由于Item[@type='Theme']匹配很多项目,你最有可能得到NodeList(php.net/manual/en/class.domnodelist.php),而不是一个空数组-请检查返回的类型。在这种情况下,您需要遍历项目。如果您只想获得单个商品,请使用唯一商品选择器,例如Item[@ID='19809']来测试XPath是否真的有效。此外,您可能需要转换为(字符串)返回的结果,否则XPath可能返回节点对象而不是值。
大约 2 年之前 回复

1个回答

The result of SimpleXMLElement::xpath() is always an array of SimpleXMLElement objects (or false for an invalid expression). SimpleXMLElement object represent element nodes, but the extension does some magic for text nodes and attributes.

Stripping down the code from the question into an example:

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

Output:

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

The result is an array with a single SimpleXMLElement that contains the text. You can use array_map() to cast all returned objects to strings.

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

Output:

array(1) {
  [0]=> 
  string(7) "Loisirs" 
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐