Skip to content
Advertisement

using simple XML (php to change one attribute)

I have an xml input in the form of a string and I want to look at it and find a particular element and modify it.

The part of the xml input I’m interested in looks like this and is part of the hierarchy of the in the string

<com:GTe Type="GTe" xmlns:com="http://xyx.com/Gte">
    <com:Cd ED="2021-07" Number="0123456789"/>
</com:GTe>

the ED element varies so im only interested in identifying all of the com:Cd children where it has a Number Attribute and then changing all but the last three digits of the number attribute to another string.

The project uses Symfony and simple XML php but I’m not sure how to do this as other parts of the xml use the Number key for other data.

Tried the following

 $message = 
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <uv:HCRReq
         <com:GTe Type="GTe" xmlns:com="http://xyx.com/Gte">
             <com:Cd ED="2021-07" Number="0123456789"/>
         </com:GTe>
      </uv:HCRReq>
   </soapenv:Body>
</soapenv:Envelope>';

    $xmlstring = simplexml_load_string($message);

    //currently not working
    $number = $xmlstring->soapenv:Envelope->soapenv:Body->uv:HCRReq->com:GTe->com:CD->number;

    $length = strlen($number);
    //need to check length is 11 or 12 long

    $alteredNum = '1234567'.substr($number,length-3,3);

// Not sure how to set the string

Advertisement

Answer

Can you try this:

$message =
    '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <uv:HCRReq>
         <com:GTe Type="GTe" xmlns:com="http://xyx.com/a">
             <com:Cd ED="2021-07" Number="012345678999"/>
         </com:GTe>
      </uv:HCRReq>
   </soapenv:Body>
</soapenv:Envelope>';

$xml = simplexml_load_string($message);

$nodes = $xml->xpath('//*[name()="com:Cd" and @Number]');
if ($nodes) {
    $number = (string)$nodes[0]->attributes()['Number'];
    if (12 === strlen($number) || 11 === strlen($number)) {
        unset($nodes[0]->attributes()['Number']);
        $nodes[0]->addAttribute('Number', '111' . substr($number, -3, 3));
    }
}

print_r($xml->asXML());

Result:

<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <uv:HCRReq>
         <com:GTe xmlns:com="http://xyx.com/a" Type="GTe">
             <com:Cd ED="2021-07" Number="111999"/>
         </com:GTe>
      </uv:HCRReq>
   </soapenv:Body>
</soapenv:Envelope>

Although it seems the <uv:HCRReq xml start tag is missing the> but that might have been a copy paste issue.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement