Example of mutual conversion function between XML and array in PHP

高洛峰
Release: 2023-03-05 17:06:01
Original
1315 people have browsed it

This article mainly introduces the mutual conversion function of php to realize XML and array, and analyzes the related operation skills of php to realize xml to array and array to xml in combination with examples. Friends in need can refer to this article

The example describes the mutual conversion function of XML and array in PHP. Share it with everyone for your reference, the details are as follows:

Convert array 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();
}
Copy after login

Convert xml to array:

function xmltoarr($path){
  $xmlfile = file_get_contents($path);//提取xml文档中的内容以字符串格式赋给变量
  $ob= simplexml_load_string($xmlfile);//将字符串转化为变量
  $json = json_encode($ob);//将对象转化为JSON格式的字符串
  $configData = json_decode($json, true);//将JSON格式的字符串转化为数组
  print_r($configData);
}
Copy after login

For more examples of mutual conversion functions between XML and arrays in PHP, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!