Here is an XML bit:
[11] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 46e8f57e67db48b29d84dda77cf0ef51
[label] => Publications
)
[section] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 9a34d6b273914f18b2273e8de7c48fd6
[label] => Journal Articles
[recordId] => 1a5a5710b0e0468e92f9a2ced92906e3
)
I know the value "46e8f57e67db48b29d84dda77cf0ef51" but its location varies across files. Can I use XPath to find the path to this value? If not what could be used?
Latest trial that does not work:
$search = $xml->xpath("//text()=='047ec63e32fe450e943cb678339e8102'");
while(list( , $node) = each($search)) {
echo '047ec63e32fe450e943cb678339e8102',$node,"\n";
}
Is this string always in the
@id
attribute? Then a valid and distinct path is always//*[@id='46e8f57e67db48b29d84dda77cf0ef51']
, no matter where it is.To construct a path to a given node, use
$node->getNodePath()
which will return an XPath expression for the current node. Also take this answer on constructing XPath expression using@id
attributes, similar to like Firebug does, in account.For SimpleXML you will have to do everything by hand. If you need to support attribute and other paths, you will have to add this, this code only supports element nodes.
PHPs DOMNode objects have a function for that:
DOMNode::getNodePath()
Output:
SimpleXML is a wrapper for DOM and here is a function that allows you to get the DOMNode for an SimpleXMLElement:
dom_import_simplexml
.To fetch an element by its attribute xpath can be used.
Select all nodes using the element joker anywhere in the document:
//*
Filter them by the id attribute:
//*[@id = "46e8f57e67db48b29d84dda77cf0ef51"]