这是xml
<yml_catalog date="2016-03-23 13:33">
<categories>
<category id="1" parentId="0">Test</category>
<category id="131" parentId="1">Test 1</category>
<category id="19" parentId="1">Test 2</category>
<category id="20" parentId="1">Test 3</category>
<category id="21" parentId="1">Test 4</category>
<category id="22" parentId="1">Test 5</category>
我通过xpath 获得类别id
var_dump($xmlObject->xpath("//yml_catalog/shop/categories/category[@id='22']"));die;
我得到这个输出:
array(1) {
[0] =>
class SimpleXMLElement#94 (1) {
public $@attributes =>
array(2) {
'id' =>
string(2) "22"
'parentId' =>
string(1) "1"
}
}
}
问题:如何使用xpath方法在元素中获取Text 5
?
通常使用XPath表达式,您可以使用/text()
来获取当前上下文元素的子级文本节点,或者使用string()
函数包装整个XPath,将第一个返回的元素转换为string
:
//yml_catalog/shop/categories/category[@id='22']/text()
string(//yml_catalog/shop/categories/category[@id='22'])
具体使用SimpleXML
,您可以将元素强制转换为string
,如下所示:
var_dump((string)$xmlObject->xpath("//yml_catalog/shop/categories/category[@id='22']")[0]);
演示:https://eval.in/541310
输出:string(6) "Test 5"