Marco
Marco

Reputation: 31

How to get the root with simplexml xpath function

I'm trying to get the root node of a simpleXml element, but it doesn't find anything. This is my code example:

$xml = <<<XML
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/LSP%20iShip/LSP%20Dossiers/Standard%20iShip%20Mappings/iShip%20XSD's/iOrder.xsd">
    <Reference>21EW400084SA</Reference>
    <Name>John</Name>
    <Street1>Ally 3</Street1>
    <Zipcode>0</Zipcode>
    <City>ESPANA</City>
    <CountryCode>ES</CountryCode>
</Order>
XML;

$simpleXML = simplexml_load_string($xml);

var_dump($simpleXML->xpath('/'));

var_dump results in the output:

array(0) {}

The xpath query in our main program is a variable input. It could be the root, or the path to a child. When the variable input is '/', it returns nothing (as you can see in the above example). How can I make it return the root node?

Upvotes: 3

Views: 566

Answers (2)

miken32
miken32

Reputation: 42760

The xpath query / will not return anything, because it's an empty search. The leading / says the query starts at the root, but it still needs something to search. I suspect you want to try $simpleXML->xpath('/Order') or $simpleXML->xpath('/*').

Upvotes: 1

Francis Eytan Dortort
Francis Eytan Dortort

Reputation: 1447

The proper XPath expression is /*.

var_dump($simpleXML->xpath('/*'));

or, for the SimpleXMLElement object:

var_dump($simpleXML->xpath('/*')[0]);

Upvotes: 0

Related Questions