Search code examples
phpxmlsimplexml

How to retrieve the first node of a XML after use simplexml_load_string in PHP?


I have the follow xml where the first node is the <Cancellation>

<?xml version='1.0' encoding='UTF-8'?> 
<Cancellation>
    <version>message-version</version>
    <customerID>customer-identifier</customerID>
    <invoiceID>invoice-number</invoiceID>
    <cancellationDate>yyyy-mm-dd</cancellationDate>
    <reason>reason</reason>
    <reasonCode>reason-code</reasonCode>
    <attempts>attempts-count</attempts>
    <merchantID>rocketgate merchant-identifier</merchantID>
    <merchantSiteID>site-id</merchantSiteID>
    <udf01>user-data</udf01>
</Cancellation>

Eventually I could have a similar xml but for a complete different process like registration, like the follow:

<?xml version='1.0' encoding='UTF-8'?> 
    <Registration>
        <version>message-version</version>
        <customerID>customer-identifier</customerID>
        <invoiceID>invoice-number</invoiceID>
        <merchantID>rocketgate merchant-identifier</merchantID>
        <merchantSiteID>site-id</merchantSiteID>
        <udf01>user-data</udf01>
    </Registration>

I will need to catch this first node in a if condition to redirect to the appropriate path.

Following this link I got an array from the sent xml:

$xmlString = trim(file_get_contents('php://input'));
$xmlObj    = simplexml_load_string($xmlString);
$xmlJSON = json_encode($xmlObj);
$xmlArray = json_decode($xmlJSON, true);

But the issue is that I can't see the first <Cancellation> or <Registration> node after passing the xml string to an object. enter image description here

Even the examples in the php doc is not showing the first node.

I need to test if it is a Cancellation or a Registration. How could I do that?


Solution

  • To find the tag name of the root element in XML just use getName() on the SimpleXMLElement...

    echo $xmlObj->getName();