- Array to XML Conversion and XML to Array Convert in PHP
- What is XML
- The Difference Between XML and HTML
- Convert PHP Multidimensional Array to the XML file format
- Method for generating XML
- Array to XML Complete code
- Convert XML to PHP Associative Array
- Conclusion:
- Related Posts
- PHP substr_count() Function
- How to Capture Screenshot of a Website Using PHP
- How to Add Watermark to Existing PDF using PHP
- How to convert php array to simple xml
- Example — 1 :
- Output :
- Example — 2 :
- Output :
- Convert array to XML in PHP
- PHP Array:
- Array to XML:
- XML File:
- Insert XML Into Databse
Array to XML Conversion and XML to Array Convert in PHP
Many times we need to store the data in XML format into the database or into the file. In this article, we are going to discuss how we can convert array to XML and XML to array in PHP.
Nowadays we mainly use JSON format to store and send the data from one location to another. But what if we require to store or send the data in XML format.
Let’s suppose we have to work with the third party database and to communicate to that database we have only XML API available there, then obviously we need to fetch those XML API and need to convert them in PHP array to work around. And the same thing applies when you need to provide some data using API to a third party when demands the API in XML format. In this article, we will learn how we can convert PHP simple array, associative array, or multidimensions array to XML format and vice versa.
If you are concerned about the size of the database, XML can help us to free some space from the database. You can use an XML file to save the data instead of saving data into the database you can save data in XML files and later when required you can get the data in an array using to XML to PHP conversion method that we have explained below.
What is XML
XML stands for an extensible markup language. A markup language is a set of codes, or tags, that describes the text in a digital document. XML is a software- and hardware-independent tool for storing and transporting data.
- XML stands for extensible Markup Language
- XML is a markup language much like HTML
- XML was designed to store and transport data
- XML was designed to be self-descriptive
- XML is a W3C Recommendation
The Difference Between XML and HTML
XML and HTML were designed with different goals:
- XML was designed to carry data – with a focus on what data is
- HTML was designed to display data – with a focus on how data looks
- XML tags are not predefined like HTML tags are
Convert PHP Multidimensional Array to the XML file format
$array = array( 'class'=> 'class 10th', 'student'=> array( '0' => array( 'name' => 'David', 'rollNo' => '34' ), '1' => array( 'name' => 'Sunny', 'rollNo' => '30' ), '2' => array( 'name' => 'Illa', 'rollNo' => '37' ), '3' => array( 'name' => 'Monna', 'rollNo' => '35' ) ) );
Method for generating XML
Now, you need to create a function generatXML()
function generateXML($data) < $title = $data['class']; $rowCount = count($data['student']); //create the xml document $xmlDoc = new DOMDocument(); $root = $xmlDoc->appendChild($xmlDoc->createElement("student_info")); $root->appendChild($xmlDoc->createElement("title",$title)); $root->appendChild($xmlDoc->createElement("totalRows",$rowCount)); $tabUsers = $root->appendChild($xmlDoc->createElement('rows')); foreach($data['student'] as $user)< if(!empty($user))< $tabUser = $tabUsers->appendChild($xmlDoc->createElement('student')); foreach($user as $key=>$val)< $tabUser->appendChild($xmlDoc->createElement($key, $val)); > > > header("Content-Type: text/plain"); //make the output pretty $xmlDoc->formatOutput = true; //save xml file $file_name = str_replace(' ', '_',$title).'.xml'; $xmlDoc->save($file_name); //return xml file name return $file_name; >
You only need to use generateXML() function and pass the data array in it to convert the array to XML in PHP. This function creates an XML document using DOMDocument class and inserts the PHP array content in this XML document. at the end, XML file saved as in specified location with given file name.
Array to XML Complete code
appendChild($xmlDoc->createElement("student_info")); $root->appendChild($xmlDoc->createElement("title",$title)); $root->appendChild($xmlDoc->createElement("totalRows",$rowCount)); $tabUsers = $root->appendChild($xmlDoc->createElement('rows')); foreach($data['student'] as $user)< if(!empty($user))< $tabUser = $tabUsers->appendChild($xmlDoc->createElement('student')); foreach($user as $key=>$val)< $tabUser->appendChild($xmlDoc->createElement($key, $val)); > > > header("Content-Type: text/plain"); //make the output pretty $xmlDoc->formatOutput = true; //save xml file $file_name = str_replace(' ', '_',$title).'.xml'; $xmlDoc->save($file_name); //return xml file name return $file_name; > // array $array = array( 'class'=> 'class 10th', 'student'=> array( '0' => array( 'name' => 'David', 'rollNo' => '34' ), '1' => array( 'name' => 'Sunny', 'rollNo' => '30' ), '2' => array( 'name' => 'Illa', 'rollNo' => '37' ), '3' => array( 'name' => 'Monna', 'rollNo' => '35' ) ) ); generateXML($array); ?>
4 David 34 Sunny 30 Illa 37 Monna 35
Convert XML to PHP Associative Array
For converting XML to PHP Associative Array we will use the few following steps.
- We will read the XML data from the file using file_get_contents() and convert the XML to an array using PHP.
- Convert XML string into an object using simplexml_load_string() function in PHP.
- Then incode the putput to JSON using json_encode() function.
- Convert JSON data into array using json_decode() function.
Array ( [title] => class 10th [totalRows] => 4 [rows] => Array ( [student] => Array ( [0] => Array ( [name] => David [rollNo] => 34 ) [1] => Array ( [name] => Sunny [rollNo] => 30 ) [2] => Array ( [name] => Illa [rollNo] => 37 ) [3] => Array ( [name] => Monna [rollNo] => 35 ) ) ) )
Conclusion:
We have tried to explain the above code with possible example, hope you liked the article. You can also visit How to check an array is multidimensional or not in PHP to check if array in multidimensional or not before using it in XML conversion.
Related Posts
PHP substr_count() Function
October 9, 2021 October 10, 2021
How to Capture Screenshot of a Website Using PHP
September 30, 2021 September 30, 2021
How to Add Watermark to Existing PDF using PHP
September 19, 2021 September 19, 2021
How to convert php array to simple xml
In this article, i will share with you how to convert PHP array to simple XML formate with example. as you know we need to many times convert PHP array to XML in PHP application. like when we integrate some third-party API in our application and that API only allows post data payload in XML format then we need to convert out array data payload in XML data payload.
Example — 1 :
'blub', 'foo' => 'bar', 'another_array' => array ( 'stack' => 'overflow', ), ); $xml = new SimpleXMLElement(''); array_walk_recursive($test_array, array ($xml, 'addChild')); print $xml->asXML();
Output :
Example — 2 :
// Define a function that converts array to xml. function arrayToXml($array, $rootElement = null, $xml = null) < $_xml = $xml; // If there is no Root Element then insert root if ($_xml === null) < $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : ''); > // Visit all key value pair foreach ($array as $k => $v) < // If there is nested array then if (is_array($v)) < // Call function for nested array arrayToXml($v, $k, $_xml->addChild($k)); > else < // Simply add child element. $_xml->addChild($k, $v); > > return $_xml->asXML(); > // Creating an array for demo $my_array = array ( 'name' => 'Harsukh Makwana', 'subject' => 'CS', // Creating nested array. 'contact_info' => array ( 'city' => 'Ahmedabad', 'state' => 'Gujrat', 'email' => 'contact@laravelcode.com' ), ); // Calling arrayToxml Function and printing the result echo arrayToXml($my_array);
Output :
Note : if the SimpleXMLElement not found then install » php-xml, php-simplexml » in your local.
i hope you like this solution.
Convert array to XML in PHP
Many times we need store the data as a XML into the database or into the file for later use. For fulfil this need, we will need to convert the data to XML and save the XML file. In this tutorial we will discuss, how to create XML from array in PHP. We have created a simple script for convert PHP array to XML. You can easily generate XML file from PHP array and save the XML file. You can convert all types of array like Associative array or Multidimensional arrays.
PHP Array:
At first we will store the users data into a variable ( $users_array ).
$users_array = array(
"total_users" => 3,
"users" => array(
array(
"id" => 1,
"name" => "Smith",
"address" => array(
"country" => "United Kingdom",
"city" => "London",
"zip" => 56789,
)
),
array(
"id" => 2,
"name" => "John",
"address" => array(
"country" => "USA",
"city" => "Newyork",
"zip" => "NY1234",
)
),
array(
"id" => 3,
"name" => "Viktor",
"address" => array(
"country" => "Australia",
"city" => "Sydney",
"zip" => 123456,
)
),
)
);
Array to XML:
Now we will convert the users array to XML using PHP SimpleXML . Please follow the comment tags for better understand.
//function defination to convert array to xml
function array_to_xml($array, &$xml_user_info) foreach($array as $key => $value) if(is_array($value)) if(!is_numeric($key)) $subnode = $xml_user_info->addChild("$key");
array_to_xml($value, $subnode);
>else $subnode = $xml_user_info->addChild("item$key");
array_to_xml($value, $subnode);
>
>else $xml_user_info->addChild("$key",htmlspecialchars("$value"));
>
>
>
//creating object of SimpleXMLElement
$xml_user_info = new SimpleXMLElement(" ");
//function call to convert array to xml
array_to_xml($users_array,$xml_user_info);
//saving generated xml file
$xml_file = $xml_user_info->asXML('users.xml');
//success and error message based on xml creation
if($xml_file) echo 'XML file have been generated successfully.';
>else echo 'XML file generation error.';
>
XML File:
The users.xml file contains the following xml.
xml version="1.0"?> user_info> total_users>3total_users> users> item0> id>1id> name>Smithname> address> country>United Kingdomcountry> city>Londoncity> zip>56789zip> address> item0> item1> id>2id> name>Johnname> address> country>USAcountry> city>Newyorkcity> zip>NY1234zip> address> item1> item2> id>3id> name>Viktorname> address> country>Australiacountry> city>Sydneycity> zip>123456zip> address> item2> users> user_info>
Insert XML Into Databse
If you want to save the XML into the database, then replace the $xml_file variable line with the following code line. Now you can insert $xml_file variable into the database.
$xml_file = $xml_user_info->asXML();
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question