How to convert XML to JSON in PHP
I want to convert som xml data into some pretty json data then output it into an api. The output is not the problem but it’s the formatting of the xml data. I’ve looked around, but haven’t gotten around making it as pretty as some of the online converters out there. this is the xml data structure:
<?xml version="1.0" encoding="utf-8"?>
<CatapultVariableSet>
<Variable
Name="Email"
Comment=""
EvaluatedDefinition="info@yourcompany.com">info@yourcompany.com</Variable>
<Variable
Name="StreetAddress"
Comment=""
EvaluatedDefinition="1234 Lorem Ipsum Ave.">1234 Lorem Ipsum Ave.</Variable>
<Variable
Name="MiR_250"
Comment=""
EvaluatedDefinition="MiR250">MiR250</Variable>
</CatapultVariableSet>
**Into this pretty JSON data:**
[
{
"Name": "Email",
"Comment": "",
"EvaluatedDefinition": "info@yourcompany.com",
"#text": "info@yourcompany.com"
},
{
"Name": "StreetAddress",
"Comment": "",
"EvaluatedDefinition": "1234 Lorem Ipsum Ave.",
"#text": "1234 Lorem Ipsum Ave."
},
{
"Name": "MiR_250",
"Comment": "",
"EvaluatedDefinition": "MiR250",
"#text": "MiR250"
}
]
This converter can do it: www.freeformatter.com/xml-to-json-converter.html#ad-output
But how does it make it so? I’ve been looking around for answers but my version just isn’t as pretty.. This is what I’ve tried so far, to get kind of close:
function my_awesome_func() {
$myfile = fopen("fildestination", "r") or die("Unable to open file!");
$output = fread($myfile,filesize("fildestination"));
fclose($myfile);
$json = json_encode($output);
$jsondecoded = json_decode($json, TRUE);
$simplexml = simplexml_load_string($jsondecoded);
$vars = $simplexml[0]->Variable;
$simpledecode = json_encode($simplexml, JSON_PRETTY_PRINT);
foreach($vars as $v){
$array = array(
"v_name" => $v["Name"][0],
"v_value" => $v["EvaluatedDefinition"][0]
);
$encodej = json_encode($array, JSON_PRETTY_PRINT);
echo $encodej;
}
}
Read more here: Source link