PHP convert XML to JSON

前端 未结 20 1786
生来不讨喜
生来不讨喜 2020-11-22 06:25

I am trying to convert xml to json in php. If I do a simple convert using simple xml and json_encode none of the attributes in the xml show.

$xml = simplexml         


        
20条回答
  •  迷失自我
    2020-11-22 07:18

    All solutions here have problems!

    ... When the representation need perfect XML interpretation (without problems with attributes) and to reproduce all text-tag-text-tag-text-... and order of tags. Also good remember here that JSON object "is an unordered set" (not repeat keys and the keys can't have predefined order)... Even ZF's xml2json is wrong (!) because not preserve exactly the XML structure.

    All solutions here have problems with this simple XML,

        
            Alabama
            My name is John Doe
            Alaska
        
    

    ... @FTav solution seems better than 3-line solution, but also have little bug when tested with this XML.

    Old solution is the best (for loss-less representation)

    The solution, today well-known as jsonML, is used by Zorba project and others, and was first presented in ~2006 or ~2007, by (separately) Stephen McKamey and John Snelson.

    // the core algorithm is the XSLT of the "jsonML conventions"
    // see  https://github.com/mckamey/jsonml
    $xslt = 'https://raw.githubusercontent.com/mckamey/jsonml/master/jsonml.xslt';
    $dom = new DOMDocument;
    $dom->loadXML('
        
            Alabama
            My name is John Doe
            Alaska
        
    ');
    if (!$dom) die("\nERROR!");
    $xslDoc = new DOMDocument();
    $xslDoc->load($xslt);
    $proc = new XSLTProcessor();
    $proc->importStylesheet($xslDoc);
    echo $proc->transformToXML($dom);
    

    Produce

    ["states",{"x-x":"1"},
        "\n\t    ",
        ["state",{"y":"123"},"Alabama"],
        "\n\t\tMy name is ",
        ["b","John"],
        " Doe\n\t    ",
        ["state","Alaska"],
        "\n\t"
    ]
    

    See http://jsonML.org or github.com/mckamey/jsonml. The production rules of this JSON are based on the element JSON-analog,

    This syntax is a element definition and recurrence, with
    element-list ::= element ',' element-list | element.

提交回复
热议问题