Skip to content

Instantly share code, notes, and snippets.

@pinceladasdaweb
Created November 29, 2013 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinceladasdaweb/7709307 to your computer and use it in GitHub Desktop.
Save pinceladasdaweb/7709307 to your computer and use it in GitHub Desktop.
Convert XML to JSON
<?php
class XmlToJson {
public function Parse ($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
return $json;
}
}
$cep = isset($_GET['cep']) ? $_GET['cep'] : NULL;
print XmlToJson::Parse('http://api.wscep.com/cep?key=free&val='.urlencode($cep));
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>XML to JSON</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var t = {
cep: 75250000
};
$.ajax({
url: "cep.php",
type: "GET",
data: t
}).done(function(result){
var res = jQuery.parseJSON(result);
console.log(res);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment