Kategorien
PHP XML

read XML String or File

<?php 
$string = <<<XML
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
 <soap:Body>
  <Response xmlns="http://xxx.gateway.xxx.abcd.com">
   <return>
      <transaction_id>1234567</transaction_id>
      <error_code>109</error_code>    
   </return>
  </Response>
 </soap:Body>
</soap:Envelope>
XML;

$xml = new SimpleXMLElement($string); 
$xml->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
$body = $xml->xpath("//soap:Body");
$error_code = (string)$body[0]->Response->return->error_code;
print_r($error_code); 
?> 

OR

$xml = simplexml_load_string($string); 
 $error_code = (string)$xml->children('soap', true)
                            ->Body
                            ->children()
                            ->Response
                            ->return
                            ->error_code;

Kategorien
XML

Array →XML

Normal Array to XML Format. Sometimes i ve the competetion in projects to parse to in differently formats i.e. API response formats (JSON,XML) and so on.

1.STEP
We

$data =
                [
                    'status' =>  $exception->getStatus(),
                    'error' =>   $exception->getCode(),
                    'message' =>  $exception->getMessage(),
                    'errors'  => $exception->getErrors()
                ];

2.STEP
Create SimpleXMLElement Object then pass addChild elements and then asXML does the rest.

$xmlobj = new SimpleXMLElement('<response/>');

Flip $data 😉 Keys and Values otherwise twisted
$toxml = array_flip($data); 
array_walk_recursive($toxml, array ($xmlobj, 'addChild'));

echo $xmlobj->asXML();

Best Solution for Multidimensional Arrays

 $xmlobj = new SimpleXMLElement('<response/>');
 array2XML($obj, $data);
 
echo $xmlobj->asXML();

function array2XML($obj, $array)
    {
        foreach ($array as $key => $value)
        {
            if(is_numeric($key))
                $key = 'item' . $key;

            if (is_array($value))
            {
                $node = $obj->addChild($key);
                $this->array2XML($node, $value);
            }
            else
            {
                $obj->addChild($key, htmlspecialchars($value));
            }
        }
    }