The XML Converter Package for PHP by Novak Urošević provides a simple helper to convert XML data into JSON and PHP arrays. Given an XML string, you can use the xmlToJson() and xmlToArray() methods to convert to the desired format:
$xml = <<<XML<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="book.xsd"> <title><![CDATA[The Great Gatsby]]></title> <author>F. Scott Fitzgerald</author> <year>1925</year></book>XML; $json = Convert::xmlToJson($xml, true, true, '/path/to/book.xsd');$arr = Convert::xmlToArray($xml); // Example will all optionsConvert::xmlToArray( $xmlString, namespace_in_tag_name: true, is_cdata: true, schema_path: '/path/to/schema.xsd' // or '' to enable DTD validation);
This package primarily consists of a single PHP class that you can use to convert XML. Although this package defines a Laravel service provider, the methods for converting data are static and should be used directly with the Convert class.
Main Features
- Convert XML strings to JSON and PHP arrays
- DTD and XSD validation
- Namespace tagging
- CDATA handling
- Error handling for schema validation
- Handle CDATA and empty tags gracefully
You can learn more about this package, get full installation instructions, and view the source code on GitHub.
Related: If you need an XML package with read and write functionality, consider XML Wrangler