Home > Blockchain >  How to convert XML to JSON in PHP
How to convert XML to JSON in PHP

Time:10-05

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="[email protected]">[email protected]</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": "[email protected]",
      "#text": "[email protected]"
   },
   {
      "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: https://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;

    }
}

CodePudding user response:

Is your XML always in that structure? Trying to write a universal XML to JSON translator is much, much harder than writing one for your specific use case.

If it's always the same, just pick out the parts you need from the JSON structure by name, and put them in an array in whatever structure you want. For the XML input and JSON output you give in the question, the code is as simple as this:

$sx = simplexml_load_string($xml);
$output = [];
foreach ( $sx->Variable as $variable ) {
    $output[] = [
        'Name' => (string)$variable['Name'],
        'Comment' => (string)$variable['Comment'],
        'EvaluatedDefinition' => (string)$variable['EvaluatedDefinition'],
        '#text' => (string)$variable
    ];
}
echo json_encode($output, JSON_PRETTY_PRINT);

Note the use of (string) to tell SimpleXML that you want the text content of an element or attribute, rather than an object representing it.

CodePudding user response:

json_encode() function to convert an XML string to JSON in PHP.

  • Related