SimpleXML 和 xpath 获取节点的值
SimpleXML and xpath getting a node's value
我有以下 notes.xml XML 文件。
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
还有这个PHP脚本
<?php
$xml = simplexml_load_file('notes.xml');
$result = $xml->xpath('//to');
print_r($result);
echo "<br>";
echo $result;
?>
那么,为什么会出现下面的输出呢? (没有任何价值)
Array ( [0] => SimpleXMLElement Object ( ) )
Array
$result = $xml->xpath('//to');
这将为您 return 一组 SimpleXMLElement
对象,因为您的 XML 中可能有多个 <to>
标签。为了提取文本,您应该使用
echo (string) $result[0];
将标签中的文本内容转换为字符串return。
如果你的XML总是那么简单,你也可以使用
$result = (string) $xml->to;
看看the manual for the SimpleXMLElement::xpath
method。它总是 returns 零个或多个 SimpleXMLElement
对象的数组。
如果你 echo
一个数组 - 任何数组 - 你都会得到 Array
.
这个词
如果您 echo
一个 SimpleXMLElement
对象,它将自动转换为字符串(就像您用 echo (string)$foo
代替 echo $foo
一样,如图所示在 the basic SimpleXML examples.
因此您需要查看数组内部,以获取SimpleXMLElement
对象,然后回显该对象。请记住,如果找不到匹配项,则数组将为空。
我有以下 notes.xml XML 文件。
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
还有这个PHP脚本
<?php
$xml = simplexml_load_file('notes.xml');
$result = $xml->xpath('//to');
print_r($result);
echo "<br>";
echo $result;
?>
那么,为什么会出现下面的输出呢? (没有任何价值)
Array ( [0] => SimpleXMLElement Object ( ) )
Array
$result = $xml->xpath('//to');
这将为您 return 一组 SimpleXMLElement
对象,因为您的 XML 中可能有多个 <to>
标签。为了提取文本,您应该使用
echo (string) $result[0];
将标签中的文本内容转换为字符串return。
如果你的XML总是那么简单,你也可以使用
$result = (string) $xml->to;
看看the manual for the SimpleXMLElement::xpath
method。它总是 returns 零个或多个 SimpleXMLElement
对象的数组。
如果你 echo
一个数组 - 任何数组 - 你都会得到 Array
.
如果您 echo
一个 SimpleXMLElement
对象,它将自动转换为字符串(就像您用 echo (string)$foo
代替 echo $foo
一样,如图所示在 the basic SimpleXML examples.
因此您需要查看数组内部,以获取SimpleXMLElement
对象,然后回显该对象。请记住,如果找不到匹配项,则数组将为空。