How to Convert XML to JSON in PHP?

In this post we will show you how to convert xml to json in php. we will show you different method for xml convert to json in php.

Convert XML to JSON in PHP
Convert XML to JSON in PHP

Method – 1: xml2json php

xml convert to json using json json_encode and json_decode. it is very easy way to Convert XML to JSON in PHP.

Json & Array from XML in 3 lines:

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

Method – 2 : php xml to associative array

convert xml to json using json json_encode and json_decode but using xml file. it is very easy way to convert xml to json. pass your url url and convert it in to json.

Read Also:  Remove null values from array in PHP

$xml_file = fopen("books-xml.xml", "r") or die("Unable to open this books-xml.xml file!!");
$get_xml_string =  fread($xml_file,filesize("books-xml.xml"));
// convert string of XML(xml file data) into an object
$xml_data   = simplexml_load_string($get_xml_string);
// xml to json convert
$json_data  = json_encode($xml_data);
// convert json to array
$array_data = json_decode($json_data,TRUE);

Method – 3

In this method we use XmlToJson class and json_prepare_xml function to convert xml to json.

// assign class Xml To Json
class XmlToJson
public function json_prepare_xml ($xml_url)
$get_file_contents= file_get_contents($xml_url);
$get_file_contents = str_replace(array("\n", "\r", "\t"), '', $get_file_contents);
$get_file_contents = trim(str_replace('"', "'", $get_file_contents));
$get_simple_xml = simplexml_load_string($get_file_contents);
$json_data = json_encode($get_simple_xml);
// return json
return $json_data;
$json_data =  XmlToJson::json_prepare_xml("books-xml.xml");

Method – 4

A common pitfall is to forget that json_encode() doesn’t respect elements/data with a textvalue and attribute(s). it’ll select one in all those, that means dataloss. The operate below solves that downside. If one decides to travel for the json_encode/decode method, the subsequent operate is suggested.

Read Also:  Get minimum key value of array in PHP

function json_prepare_xml($xml_object)
foreach($xml_object->childNodes as $xml_val)
} else
if($xml_object->hasAttributes() && strlen($xml_object->nodeValue)){
$xml_object->setAttribute("nodeValue", $xml_val->textContent);
$xml_val->nodeValue = "";
$xml_url = "books-xml.xml";
$xml_object = new DOMDocument();
$xml_object->loadXML( file_get_contents($xml_url) );
$string_xml = simplexml_load_string( $xml_object->saveXML() );
$json_data = json_decode( json_encode( $string_xml ) ) );