AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home PHP and MySQL

Convert Array to XML and XML to Array in PHP

Convert Array to XML and XML to Array in PHP

Lakshika Mathur by Lakshika Mathur
December 25, 2019
Reading Time: 4 mins read
0
Convert Array to XML and XML to Array in PHP

The XML (Extensible Markup Language) is a markup language that encodes documents in a machine-readable and human-readable format. Usually, you can use Extensible Markup Language to store and transport data.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

You can use XML in several ways in a web application. Therefore, if you are worried about database size and want to lessen database usage, XML can support you free up space from the database. As an alternative to a database, you can store data in an XML file and retrieve data from an XML file without connecting to the database. With the help of this tutorial, we will explain to you how to convert PHP associative or multidimensional array to XML and store it in the XML file. Also, the sample code shows how to parse the XML file and convert XML data to an array in PHP.

SEE ALSO: Convert HTML to PDF using JavaScript

Convert PHP Multidimensional Array to XML File

createXML() Function:

To use it in a better way, group together all arrays of XML conversion code in a PHP function. The CreateXML () function converts the PHP multidimensional array into an XML file. The data array needs to be passed as a parameter to the createXML () function. The CreateXML () function creates an XML document using the DOMDocument class and inserts PHP array contents into this XML document. Finally, the XML document is saved as an XML file in the specified file path.

function createXML($data) {
    $title = $data['title'];
    $rowCount = count($data['users']);
    
    //create the xml document
    $xmlDoc = new DOMDocument();
    
    $root = $xmlDoc->appendChild($xmlDoc->createElement("user_info"));
    $root->appendChild($xmlDoc->createElement("title",$title));
    $root->appendChild($xmlDoc->createElement("totalRows",$rowCount));
    $tabUsers = $root->appendChild($xmlDoc->createElement('rows'));
    
    foreach($data['users'] as $user){
        if(!empty($user)){
            $tabUser = $tabUsers->appendChild($xmlDoc->createElement('user'));
            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).'_'.time().'.xml';
    $xmlDoc->save("files/" . $file_name);
    
    //return xml file name
    return $file_name;
}

SEE ALSO: Convert HTML to MS Word Document using PHP

PHP Multidimensional Array

By using PHP we can save the following multidimensional array as XML file.

$data = array(
    'title' => 'Users Information',
    'users' => array(
        array('name' => 'John Doe', 'email' => '[email protected]'),
        array('name' => 'Merry Moe', 'email' => '[email protected]'),
        array('name' => 'Hellary Riss', 'email' => '[email protected]')
    )
);

PHP Array to XML File Conversion

You only need to createXML()  function and pass data array in it to convert array to XML in PHP.

echo createXML($data);

The example code will make the following XML document.

<?xml version="1.0"?>
<user_info>
  <title>Users Information</title>
  <totalRows>3</totalRows>
  <rows>
    <user>
      <name>John Doe</name>
      <email>[email protected]</email>
    </user>
    <user>
      <name>Merry Moe</name>
      <email>[email protected]</email>
    </user>
    <user>
      <name>Hellary Riss</name>
      <email>[email protected]</email>
    </user>
  </rows>
</user_info>

Convert XML to PHP Associative Array

Now we will read the XML data from the file and convert the XML to an array using PHP.

  • Firstly, read entire file into string using file_get_contents() function in PHP.
  • Secondly, use the simplexml_load_string() function in PHP to convert XML string into an object.
  • Thirdly, use json_encode() function to convert object into JSON.
  • At last, convert JSON data into associative array using json_decode() function.
//xml file path
$path = "files/path-to-document.xml";

//read entire file into string
$xmlfile = file_get_contents($path);

//convert xml string into an object
$xml = simplexml_load_string($xmlfile);

//convert into json
$json  = json_encode($xml);

//convert into associative array
$xmlArr = json_decode($json, true);
print_r($xmlArr);

The example code will convert the XML file to the following array.

Array
(
    [title] => Users Information
    [totalRows] => 3
    [rows] => Array
        (
            [user] => Array
                (
                    [0] => Array
                        (
                            [name] => John Doe
                            [email] => [email protected]
                        )

                    [1] => Array
                        (
                            [name] => Merry Moe
                            [email] => [email protected]
                        )

                    [2] => Array
                        (
                            [name] => Hellary Riss
                            [email] => [email protected]
                        )

                )

        )

)

Also, read our previous article- Live Image Upload, Crop and Resize using jQuery and PHP

Tags: PHPXML
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
How to Generate QR Code with PHP using Google Chart API
PHP and MySQL

How to Generate QR Code with PHP using Google Chart API

January 1, 2020
83
Next Post
Build CRUD DataGrid

Build CRUD DataGrid with jQuery EasyUI using PHP and MySQL

Convert HTML to MS Word Document using PHP

Convert HTML to MS Word Document using PHP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version