Convert XML to JSON Correctly With PHP Code Examples (2023)

Code Snippet: XML to JSON in PHP This article focuses on converting XML to JSON in PHP. You can convert XML to JSON using 2 functions. Here's the relevant code snippet to transform XML to JSON. <?php $employees_xml = '&lt;employees> &lt;employee id="1"> &lt;firstname>Jack&lt;/firstname> &lt;lastname>Nesham&lt;/lastname> &lt;age>22&lt;/age> &lt;role>Software Engineer&lt;/role> &lt;/employee> &lt;employee id="2"> &lt;firstname>Maxwell&lt;/firstname> &lt;lastname>Rick&lt;/lastname> &lt;age>25&lt;/age> &lt;role>DevOps Engineer&lt;/role> &lt;/employee> &lt;/employees>'; $xml = simplexml_load_string($employees_xml); $json = json_encode($xml, JSON_PRETTY_PRINT); ?> That's not the only way, though. This is a solid solution in many cases, but you may encounter a more complex situation, need more flexibility, or you need this in several locations. There is a solid 3rd party composer package to convert XML to CSV which we'll discuss further in the article. Relevant Content: XML & JSON Conversion Converting PHP XML to JSON In the article, “How to convert JSON to XML in PHP”,  we learned about SimpleXMLElement class and json_decode function that helps in…

read more