PHP convert XML to JSON

前端 未结 20 1785
生来不讨喜
生来不讨喜 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:06

    This is an improvement of the most upvoted solution by Antonio Max, which also works with XML that has namespaces (by replacing the colon with an underscore). It also has some extra options (and does parse John correctly).

    function parse_xml_into_array($xml_string, $options = array()) {
        /*
        DESCRIPTION:
        - parse an XML string into an array
        INPUT:
        - $xml_string
        - $options : associative array with any of these keys:
            - 'flatten_cdata' : set to true to flatten CDATA elements
            - 'use_objects' : set to true to parse into objects instead of associative arrays
            - 'convert_booleans' : set to true to cast string values 'true' and 'false' into booleans
        OUTPUT:
        - associative array
        */
    
        // Remove namespaces by replacing ":" with "_"
        if (preg_match_all("||", $xml_string, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                $xml_string = str_replace('<'. $match[1] .':'. $match[2], '<'. $match[1] .'_'. $match[2], $xml_string);
                $xml_string = str_replace('

提交回复
热议问题