欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP中數(shù)組轉(zhuǎn)換為SimpleXML教程

 更新時間:2019年01月27日 15:28:24   投稿:laozhang  
在本篇文章中我們給大家總結(jié)了一篇關(guān)于PHP中數(shù)組轉(zhuǎn)換為SimpleXML教程內(nèi)容,有需要的朋友們跟著學習參考下。

SimpleXML擴展函數(shù)提供了將XML轉(zhuǎn)換為對象的工具集。這些對象處理普通的屬性選擇器和數(shù)組迭代器。

示例1:

<?php 
// 將php數(shù)組轉(zhuǎn)換為xml文檔的代碼
 
//定義一個將數(shù)組轉(zhuǎn)換成xml的函數(shù)。
function arrayToXml($array, $rootElement = null, $xml = null) { 
  $_xml = $xml; 
    
  // 如果沒有$rootElement,則插入$rootElement
  if ($_xml === null) { 
    $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>'); 
  } 
    
  // 訪問所有鍵值對 
  foreach ($array as $k => $v) { 
      
    // 如果有嵌套數(shù)組 
    if (is_array($v)) { 
        
      // 調(diào)用嵌套數(shù)組的函數(shù)
      arrayToXml($v, $k, $_xml->addChild($k)); 
      } 
        
    else { 
        
        
      $_xml->addChild($k, $v); 
    } 
  } 
    
  return $_xml->asXML(); 
} 
  
// 創(chuàng)建一個用于演示的數(shù)組 
$my_array = array ( 
'name' => 'GFG', 
'subject' => 'CS', 
  
  // 創(chuàng)建嵌套數(shù)組。
  'contact_info' => array ( 
  'city' => 'Noida', 
  'state' => 'UP', 
  'email' => '448199179@qq.com'
  ), 
); 
  
// 調(diào)用arrayToxml函數(shù)并打印結(jié)果
echo arrayToXml($my_array); 
?>

輸出:

<?xml version="1.0"?>
<root>
  <name> GFG </name>
  <subject> CS </subject>
  <contact_info >
    <city > Noida < /city >
    <state > UP < /state >
    <email > 448199179@qq.com </email>
  <contact_info>
<root>

可以使用array_walk_recursive()函數(shù)解決上述問題。此函數(shù)將數(shù)組轉(zhuǎn)換為xml文檔,其中數(shù)組的鍵轉(zhuǎn)換為值,數(shù)組的值轉(zhuǎn)換為xml的元素。

示例2:

<?php 
// 將php數(shù)組轉(zhuǎn)換為xml文檔的代碼
//創(chuàng)建一個數(shù)組
$my_array = array ( 
  'a' => 'x', 
  'b' => 'y', 
    
  // creating nested array 
  'another_array' => array ( 
    'c' => 'z', 
  ), 
); 
  
// 這個函數(shù)使用root元素創(chuàng)建一個xml對象。
$xml = new SimpleXMLElement('<root/>'); 
  
// 這個函數(shù)重新將數(shù)組元素添加到xml文檔中
array_walk_recursive($my_array, array ($xml, 'addChild')); 
  
// 這個函數(shù)打印xml文檔。 
print $xml->asXML(); 
?>

輸出:

<?xml version =“1.0”?> <root> 
    <x> a </ x> 
    <y> b </ y> 
    <z> c </ z> </ root>

注:

如果系統(tǒng)生成錯誤類型:

PHP Fatal error: Uncaught Error: Class ‘SimpleXMLElement' not found in /home/6bc5567266b35ae3e76d84307e5bdc78.php:24 ,

那么只需安裝php-xml,php-simplexml軟件包。

相關(guān)文章

最新評論