php-laravelHow can I convert JSON data to XML using PHP Laravel?
To convert JSON data to XML using PHP Laravel, you can use the json_encode()
and simplexml_load_string()
functions.
Example code
$json = '{"name": "John", "age": 30, "city": "New York"}';
$json_array = json_decode($json, true); // convert JSON to array
$xml = simplexml_load_string("<root></root>"); // create a new XML element
array_walk_recursive($json_array, array ($xml, 'addChild')); // add array elements to XML
print $xml->asXML(); // output XML
Output example
<?xml version="1.0"?>
<root>
<name>John</name>
<age>30</age>
<city>New York</city>
</root>
Code explanation
json_decode()
: converts a JSON string to a PHP arraysimplexml_load_string()
: creates a new SimpleXMLElement object from a given stringarray_walk_recursive()
: iterates over each element of an array and applies a user-defined function to each elementaddChild()
: adds an element to the SimpleXMLElement objectasXML()
: outputs the XML in a string
Helpful links
More of Php Laravel
- How do I set up a Laravel worker using PHP?
- How do I use Laravel traits in PHP?
- How can I use PHP, Laravel, and Vue together to create a web application?
- How do I set up a .gitlab-ci.yml file for a Laravel project using PHP?
- How do I use PHP Laravel Tinker to debug my code?
- How do I set the timezone in PHP Laravel?
- How can I get the current year in PHP Laravel?
- How do I write a unit test in Laravel using PHP?
- How do I use a template in Laravel with PHP?
- How do I run a seeder in Laravel using PHP?
See more codes...