Json Encode or Serialize an XML

后端 未结 5 1275
-上瘾入骨i
-上瘾入骨i 2020-12-22 06:01

I have some xml, this is a simple version of it.



  item one
  item two         


        
5条回答
  •  萌比男神i
    2020-12-22 06:21

    You can go the route with json_encode and json_decode and you can add the stuff you're missing because that json_encode-ing follows some specific rules with SimpleXMLElement.

    If you're interested into the rules and their details, I have written two blog-posts about it:

    • SimpleXML and JSON Encode in PHP – Part I
    • SimpleXML and JSON Encode in PHP – Part II

    For you perhaps more interesing is the third part which shows how you can modify the json serialization and provide your own format (e.g. to preserve the attributes):

    • SimpleXML and JSON Encode in PHP – Part III and End

    It ships with a full blown example, here is an excerpt in code:

    $xml = '
    
      item one
      item two
    
    ';
    
    $obj = simplexml_load_string($xml, 'JsonXMLElement');
    
    echo $json = json_encode($obj, JSON_PRETTY_PRINT), "\n";
    
    print_r(json_decode($json, TRUE));
    

    Output of JSON and the array is as following, note that the attributes are part of it:

    {
        "items": {
            "item": [
                {
                    "@attributes": {
                        "abc": "123"
                    },
                    "@text": "item one"
                },
                {
                    "@attributes": {
                        "abc": "456"
                    },
                    "@text": "item two"
                }
            ]
        }
    }
    Array
    (
        [items] => Array
            (
                [item] => Array
                    (
                        [0] => Array
                            (
                                [@attributes] => Array
                                    (
                                        [abc] => 123
                                    )
    
                                [@text] => item one
                            )
    
                        [1] => Array
                            (
                                [@attributes] => Array
                                    (
                                        [abc] => 456
                                    )
    
                                [@text] => item two
                            )
    
                    )
    
            )
    
    )
    

提交回复
热议问题