Last active
August 29, 2015 14:08
-
-
Save darkaico/184f9f61dde4842ca3d9 to your computer and use it in GitHub Desktop.
XML to Json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Php JsonConverter | |
* | |
* @author Ariel Parra <darkaico@gmail.com> | |
* @version 0.4.0 | |
* | |
*/ | |
class JsonConverter { | |
/** | |
* Receive an XML as a String and returns a JSON | |
*/ | |
public function xmlStringToJson($xmlString) { | |
$result = ''; | |
// If the encoding its UTF-8 we are going to clean the string | |
if(mb_detect_encoding($xmlString, 'UTF-8')) { | |
// Remove the line breaks, tabs and carriage return | |
$xmlString = str_replace(array("\t", "\n", "\r"), '', $xmlString); | |
// Change double quotes by simple one | |
$xmlString = trim(str_replace('"', "'", $xmlString)); | |
} | |
// Parse the XML and covert it into an array | |
// We also merge the CDATA to a text node | |
$xmlStringArray = new SimpleXMLElement($xmlString, LIBXML_NOCDATA); | |
// Encode the array into a json object | |
$result = json_encode((array) $xmlStringArray); | |
return $result; | |
} | |
/** | |
* Receive an XML path and returns a JSON | |
*/ | |
public function xmlFileToJson($xmlFilePath) { | |
$result = ''; | |
// Check if the file exists | |
file_exists($xmlFilePath) or die('Could not find file ' . $xmlFilePath); | |
// Obtain the String | |
$xmlString = file_get_contents($xmlFilePath); | |
$result = JsonConverter::xmlStringToJson($xmlString); | |
return $result; | |
} | |
/** | |
* Receive an XML URL and returns a JSON | |
*/ | |
public function xmlURLToJson($xmlStringURL) { | |
$result = ''; | |
$xmlString = file_get_contents($xmlStringURL); | |
$result = JsonConverter::xmlStringToJson($xmlString); | |
return $result; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment