PHP
Trending

Convert XML to JSON In PHP.

Convert XML to JSON In PHP.

In this post, we will learn how to convert XML to JSON. We can convert XML to JSON by using PHP inbuilt 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 into 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 into JSON representation.

Let us see the below example to convert XML to JSON.

Create an XML like the 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 below code.

<?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.

Auto Save Example In PHP &#038; MYSQL.            Upload Image In Angular With PHP

Related Articles

Leave a Reply

Check Also
Close
Back to top button