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 = '<employees> <employee id="1"> <firstname>Jack</firstname> <lastname>Nesham</lastname> <age>22</age> <role>Software Engineer</role> </employee> <employee id="2"> <firstname>Maxwell</firstname> <lastname>Rick</lastname> <age>25</age> <role>DevOps Engineer</role> </employee> </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…