溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在PHP中將數(shù)組轉(zhuǎn)換為SimpleXML

發(fā)布時間:2020-12-17 15:15:58 來源:億速云 閱讀:153 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了怎么在PHP中將數(shù)組轉(zhuǎn)換為SimpleXML,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

SimpleXML擴(kuò)展函數(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 ,

上述內(nèi)容就是怎么在PHP中將數(shù)組轉(zhuǎn)換為SimpleXML,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI