Tulho Melo
Tulho Melo

Reputation: 35

Convert only parts of XML to JSON

I have this XML (example):

<rows>
    <row id="123">
        <district>123</district>
        <email>[email protected]</email>
        <area>V</area>
    </row>
</rows>

I get that online XML from a URL. And I'm converting to JSON with the following PHP code: ($url is the variable with the URL of my XML above.)

<?php

class XmlToJson {

    public function Parse ($url) {

        $file = file_get_contents($url);
        $file = str_replace(array("\n", "\r", "\t"), '', $file);
        $file = trim(str_replace('"', "'", $file));

        $simpleXml = simplexml_load_string($file);
        $json = json_encode($simpleXml);
        return $json;
    }
}
?>

Which returns (example):

{
   "rows": {
      "row": [
         {
            "@attributes": {
               "id": "4310"
            },
            "district": "123",
            "email": "[email protected]",
            "area": "V"
         }
      ]
   }
}

How do I generate the JSON without these tags "rows" and "row"?

Upvotes: 1

Views: 277

Answers (1)

Ray
Ray

Reputation: 41428

Your example XML string with a single row returns this json :

 {"row":{"@attributes":{"id":"123"},"district":"123","email":"[email protected]","area":"V"}}

I'm assuming to get the json your example there are additional tags surrounding the <rows> tag like

<xml>
 <rows>
<row id="123">
    <district>123</district>
    <email>[email protected]</email>
    <area>V</area>
</row>
</rows>
</xml>

Simple XML coverts your xml string to an object. Just access the specific property of the generated object you want to convert json.

Try this:

 $json = json_encode($simpleXml->rows->row);

Upvotes: 1

Related Questions