PHP中的XPath Regex不起作用
以下是我返回的XML:
<?xml version="1.0" encoding="utf-8"?>
<lists>
<list>
<id>6791</id>
<title><![CDATA[List 1]]></title>
<type>0</type>
<priority>0</priority>
<due><![CDATA[0000-00-00 00:00:00]]></due>
<notes><![CDATA[]]></notes>
<user_id>49211</user_id>
<owner><![CDATA[]]></owner>
<item1>
<done>0</done>
<title><![CDATA[Bamboo Montage-83 Knee High Studded Contrast Colored Zipper Riding Boot - Brown PU]]></title>
<barcode>B00H2Y2UY6</barcode>
<priority>2</priority>
<item_id>57741</item_id>
</item1>
<item2>
<done>0</done>
<title><![CDATA[List 2]]></title>
<barcode><![CDATA[]]></barcode>
<priority>2</priority>
<item_id>57751</item_id>
</item2>
<item3>
<done>0</done>
<title><![CDATA[List Item 1]]></title>
<barcode><![CDATA[]]></barcode>
<priority>2</priority>
<item_id>57761</item_id>
</item3>
</list>
我想获取带有数字的list->item[0-9]
节点,我正在使用PHP的SimpleXMLElement
类来获取它们,但我无法使用正则表达式获取节点。以下是我的代码:
foreach ($list_xml->lists->xpath("/list/^item[0-9]$") as $listItem) {
echo $listItem->title;
}
注意$LIST_XML的转储如下所示:
SimpleXMLElement Object
(
[lists] => SimpleXMLElement Object
(
[list] => Array
(
[0] => SimpleXMLElement Object
(
[id] => 6791
[title] => SimpleXMLElement Object
(
)
[type] => 0
[priority] => 0
[due] => SimpleXMLElement Object
(
)
[notes] => SimpleXMLElement Object
(
)
[user_id] => 49211
[owner] => SimpleXMLElement Object
(
)
[item1] => SimpleXMLElement Object
(
[done] => 0
[title] => SimpleXMLElement Object
(
)
[barcode] => B00H2Y2UY6
[priority] => 2
[item_id] => 57741
)
[item2] => SimpleXMLElement Object
(
[done] => 0
[title] => SimpleXMLElement Object
(
)
[barcode] => SimpleXMLElement Object
(
)
[priority] => 2
[item_id] => 57751
)
[item3] => SimpleXMLElement Object
(
[done] => 0
[title] => SimpleXMLElement Object
(
)
[barcode] => SimpleXMLElement Object
(
)
[priority] => 2
[item_id] => 57761
)
)
)
)
解决方案
SimpleXmlElement
由只支持XPath 1.0
的libxml2支持。XPath 1.0
不支持与正则表达式的字符串匹配,XPath 2.0
支持。
因此有两个选项处于打开状态:
选项1:继续使用XPath 1.0
在这种情况下,您可以尝试动态构建XPath查询以匹配所有item*
节点:
$items=array();
for($i=0; $i<10; $i++) {
$items[] = '/list/item' . $i;
}
$xpath=join($items, '|'); // $xpath == '/list/item1|/list/item2| ...'
选项2:迁移到XPath 2.0
没有将此支持添加到PHP的计划。阅读这个SO问题: (What is the best way to use XSLT 2.0 with PHP?)用于查找解决办法。在撰写本文时,它是关于这个主题的最真实的文章之一。
相关文章