Example of conversion between XML and array in php

Source: Internet
Author: User
This article mainly introduces php's ability to convert XML and arrays into one another, and analyzes the xml-to-array and array-to-xml operations in the form of examples, for more information about how to convert XML and arrays in php, see the next article. This article describes how to convert xml to arrays in php and how to convert arrays to xml using examples, for more information, see

This example describes how php converts XML and arrays. We will share this with you for your reference. The details are as follows:

Convert arrays to xml:

function arrtoxml($arr,$dom=0,$item=0){  if (!$dom){    $dom = new DOMDocument("1.0");  }  if(!$item){    $item = $dom->createElement("root");    $dom->appendChild($item);  }  foreach ($arr as $key=>$val){    $itemx = $dom->createElement(is_string($key)?$key:"item");    $item->appendChild($itemx);    if (!is_array($val)){      $text = $dom->createTextNode($val);      $itemx->appendChild($text);    }else {      arrtoxml($val,$dom,$itemx);    }  }  return $dom->saveXML();}

Convert xml into an array:

Function xmltoarr ($ path) {$ xmlfile = file_get_contents ($ path); // extract the content in the xml document and assign it to the variable $ ob = simplexml_load_string ($ xmlfile) in string format ); // convert the string to the variable $ json = json_encode ($ ob); // Convert the object to a JSON string $ configData = json_decode ($ json, true ); // Convert a JSON string to an array print_r ($ configData );}

For more articles about how to convert XML and array functions in php, refer to PHP!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.