PHP convert XML to JSON

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

    If you would like to only convert a specific part of the XML to JSON, you can use XPath to retrieve this and convert that to JSON.

    xpath('/states/state[@id="AL"]')[0]; // [0] gets the node
    echo json_encode($xml_Excerpt);
    ?>
    

    Please note that if you Xpath is incorrect, this will die with an error. So if you're debugging this through AJAX calls I recommend you log the response bodies as well.

提交回复
热议问题