Php 用xpath解析xml值元素
这是xmlPhp 用xpath解析xml值元素,php,xml,xpath,Php,Xml,Xpath,这是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"
<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方法获取元素中的
文本5
?通常,使用xpath表达式,您可以使用/Text()
获取当前上下文元素的子级文本节点,或者使用字符串()
函数包装整个xpath,将第一个返回的元素转换为字符串
:
//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]);
演示:
输出:
字符串(6)“测试5”
如果您只想从属性id为22的category元素中获取文本内容,请将/.
或/text()
添加到xpath中
var_dump((string)$xmlObject->xpath("//yml_catalog/shop/categories/category[@id='22']")[0]);