Convert XML to JSON in PHP.

Posted on

In this post, we will learn how to convert XML to JSON. We can convert XML to JSON using PHP built-in function. These functions are simplexml_load_file and json_encode.

What is simplexml_load_file?

This function converts an XML file into an object. It accepts the absolute path of an XML file as a parameter, converts it to an object of the SimpleXMLElement class and returns it.

What is json_encode?

It returns the JSON representation of a value. It is used to convert an array or object to JSON representation.

Let’s see the example below to convert XML to JSON.

Create an XML like below.

<?xml version="1.0" encoding="UTF-8" ?>
<root>
  <row>
    <id>4051</id>
    <name>manoj</name>
    <email>manoj@gmail.com</email>
    <password>Test@123</password>    
    <dob/>
    <gender>0</gender>     
  </row>
  <row>
    <id>4050</id>
    <name>pankaj</name>
    <email>p1@gmail.com</email>
    <password>Test@123</password>    
    <gender>0</gender> 
  </row>
  <row>
    <id>3050</id>
    <name>Neeraj1993</name>
    <email>neeraj.singh@adequateinfosoft.com</email>
    <password>286956</password>    
    <gender>0</gender>    
  </row>
  <row>
    <id>3049</id>
    <name>Sophia</name>
    <email>sophia@gmail.com</email>
    <password>Test@123</password>    
    <dob>2019-12-19T11:54:19</dob>
    <gender>2</gender>       
  </row>
  <row>
    <id>3048</id>
    <name>Raju Prasad</name>
    <email>raju.nsit@gmail.com</email>
    <password>Raju@1234</password>   
    <dob>2019-12-01T01:55:34</dob>
    <gender>1</gender>   
  </row>  
</root>

Create a PHP file and add the code below.

<?php  
    $obj = simplexml_load_file('filename.xml');
    $data = json_encode($xmlObject, JSON_PRETTY_PRINT);      
    print_r($data);
?>

Above are the steps to convert XML to JSON in PHP.

Example of automatic recording in PHP & MYSQL. Download an image in Angular with PHP

Leave a Reply

Your email address will not be published.