PHP Parse and Process XML data

  340 views   11 months ago PHP

Sometimes working with 3rd party API, you may get response in the xml format instead of json. XML is a extensible markup language like HTML. XML is used to store and send data like json. PHP already have SimpleXML class to handle xml data. The simplexml_load_string() function in PHP is used to handle an XML data and returns an object.

Syntax:

simplexml_load_string($xml, $class_name, $options, $ns, $is_prefix);

Where:

xml is xml formated data
$class_name is optional parameter so that simplexml_load_string() will return an object of the specified class.
$options is also optional parameter for Libxml parameters is set by specifying the option and 1 or 0.
$ns is optional prefix or URI.
$is_prefix is optional boolean value true if ns is a prefix, false if it's a URI; defaults to false.

Let's have look bellow example.

<?php

$string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<mail>
  <to>Tove</to>
  <from>Jani</from>
  <subject>Greeting</subject>
  <body>What's up?</body>
</mail>
XML;

$xml = simplexml_load_string($string);

print_r($xml);

The above example will print:

SimpleXMLElement Object
(
  [to] => Tove
  [from] => Joe
  [subject] => Greeting
  [body] => What's up?
)

You can access its property with single arrow key:

print_r($xml->body); // What's up?

If you want to convert xml to PHP array, just convert object to json object and then convert it to PHP array.

<?php

$string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<mail>
  <to>Tove</to>
  <from>Jani</from>
  <subject>Greeting</subject>
  <body>What's up?</body>
</mail>
XML;

$xml_object = simplexml_load_string($string);
$xml_json = json_encode($xml_object);
$xml_array = json_decode($xml_json, true);

print_r($xml_array);

This will print below output.

Array
(
  [to] => Tov
  [from] => Jani
  [subject] => Greeting
  [body] => What's up?
)

This way you can handle xml string data and convert it to PHP array or object.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]