Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 用xpath解析xml值元素_Php_Xml_Xpath - Fatal编程技术网

Php 用xpath解析xml值元素

Php 用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"

这是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方法获取元素中的
文本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]);