How to parse and process XML data in 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.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment