问题
Here is my XML that is returned:
<?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>
i wanted to get the list->item[0-9]
node which is appended with a number i am using PHP's SimpleXMLElement
class to get them but i am unable to get the node with regular expression here is my code:
foreach ($list_xml->lists->xpath("/list/^item[0-9]$") as $listItem) {
echo $listItem->title;
}
note a dump of $list_xml is like this:
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
)
)
)
)
回答1:
SimpleXmlElement
is backed by libxml2 which supports XPath 1.0
only. XPath 1.0
doesn't support string matching with regular expressions, XPath 2.0
does.
So two options are open:
Option 1: Stay with XPath 1.0
In this case, you can try to build on the fly the xpath query for matching all the item*
nodes:
$items=array();
for($i=0; $i<10; $i++) {
$items[] = '/list/item' . $i;
}
$xpath=join($items, '|'); // $xpath == '/list/item1|/list/item2| ...'
Option 2: Move to XPath 2.0
There is no plan for adding this support to PHP. Read this SO question: (What is the best way to use XSLT 2.0 with PHP?) for finding a workaround. As of this writing, it is one of the most actual about this subject.
来源:https://stackoverflow.com/questions/21138875/xpath-regex-in-php-not-working