Reading XML file and generating Json_encode and Json_decode to out put xml content as php array

Reading XML File

// array declaration
$file_data = array();
// xml file/path
$xml_file = “some_xml_file.xml”;
// read xml file
$xml = simplexml_load_file($xml_file);
if($xml){
$encode_content = json_encode($xml);
$decode_content = json_decode( $encode_content , 1);
}
// out puts json encoded value of the content in the XML file
echo $encode_content;
// out puts XML file content as php array
print_r($decode_content);

 

Reading XML file with CDATA

// array declaration
$file_data = array();

// The XML data file with CDATA tags and whitespace such as tabs
$xml_file = “some_xml_file.xml”;
// Load xml data.
$xml = file_get_contents($xml_file);
// Strip whitespace between xml tags
$xml = preg_replace(‘~\s*(<([^>]*)>[^<]*</\2>|<[^>]*>)\s*~’, ‘$1’, $xml);
// Convert CDATA into xml nodes.
$xml = simplexml_load_string($xml,’SimpleXMLElement’, LIBXML_NOCDATA);
if($xml){
$encode_content = json_encode($xml);
$decode_content = json_decode( $encode_content , 1);
}

// out puts json encoded value of the content in the XML file
echo $encode_content;
// out puts XML file content as php array
print_r($decode_content);

 

Note :

We can use
$xml = simplexml_load_file($xml_file,’SimpleXMLElement’, LIBXML_NOCDATA);
but this gives white spaces in the CDATA content.



			

Leave a Reply

Your email address will not be published. Required fields are marked *