簡體   English   中英

將PHP數組轉換為XML?

[英]Converting a PHP array to XML?

說我有一個像這樣的數組:

<?php
$colors=array();

$colors[0]['id']=1;
$colors[0]['color']='blue';


$colors[1]['id']=2;
$colors[1]['color']='green';

......
?>

將整個數組轉換為XML的最簡單方法是什么?

您可以為自己創建一個僅輸出它的簡單函數。 例如,將帶有元素的數組傳遞給函數,並告訴其父元素(文檔的根元素)的名稱以及每個元素的名稱。

我認為colors家長和color的每個元素。

我還假設命名的鍵是color元素的子代:

function xml_from_indexed_array($array, $parent, $name) {

    echo '<?xml version="1.0"?>', "\n";
    echo "<$parent>\n";
    foreach ($array as $element) {
        echo "  <$name>\n";
        foreach ($element as $child => $value) {
            echo "    <$child>$value</$child>\n";
        }
        echo "  </$name>\n";
    }
    echo "</$parent>\n";
}

如您所見,這很簡單,只是遍歷所有元素。

用法示例:

<?php
$colors = array();

$colors[0]['id']    = 1;
$colors[0]['color'] = 'blue';

$colors[1]['id']    = 2;
$colors[1]['color'] = 'green';

xml_from_indexed_array($colors, 'colors', 'color');

示例輸出:

<?xml version="1.0"?>
<colors>
  <color>
    <id>1</id>
    <color>blue</color>
  </color>
  <color>
    <id>2</id>
    <color>green</color>
  </color>
</colors>

如果您具有嵌套更深的更高級的數組結構,則可能需要以遞歸的方式解決。 一些相關的問題:

我花了很多時間才能做到這一點。 我真的不敢相信PHP沒有為您做到這一點的功能。 無論如何,我希望這對某人有幫助。 請享用!

<?php
class Xml
{
  public function getXmlFromArray($value, \SimpleXMLElement &$xmlElement, $entity, $starting = null)
{

    $handleValue = function($value){
        $entityHandler = $this->getEntityHandler();
        if($entityHandler && $entityHandler instanceof \Closure){
            $value = $entityHandler($value);
        }
        if(is_string($value)){
            $value = htmlspecialchars($value);
        }
        return $value;
    };
    $addChild = function($name, $value, &$subNode = null)use(&$xmlElement, $handleValue, $entity){
        if(is_array($value)){
            if(!$subNode instanceof \SimpleXMLElement){
                $currentKey = key($value);
                $initialValue = null;
                if(is_numeric($currentKey)){
                    if(!is_array($value[$currentKey])){
                        $initialValue = $value[$currentKey];
                        unset($value[$currentKey]);
                    }
                }
                $subNode = $xmlElement->addChild($this->cleanXmlTagName($name), $initialValue);
            }
            $this->getXmlFromArray($handleValue($value), $subNode, $name);
        } else {
            $xmlElement->addChild($this->cleanXmlTagName($name), $handleValue($value));
        }
    };

    if(is_array($value))
    {
        if(is_numeric(key($value))){
            $setSubNodePrimitiveValue = function($value)use(&$xmlElement, $entity, $handleValue){
                $value = $handleValue($value);
                $children = $xmlElement->children();
                $children[] = $value;
            };
            foreach ($value as $item)
            {
                if(!is_array($item)){
                    $setSubNodePrimitiveValue($item);
                } else {
                    if($starting === true){
                        $addChild($entity, $item);
                    } else {
                        $addChild($entity, $item, $xmlElement);
                    }
                }
            }
        } else {
            foreach ($value as $subEntity => $subEntityItem)
            {
                if(is_array($subEntityItem) && is_array(current($subEntityItem)) && is_numeric(key($subEntityItem))){
                    $this->getXmlFromArray($subEntityItem, $xmlElement, $subEntity, true);
                    continue;
                }
                $addChild($subEntity, $subEntityItem);
            }
        }
    } else {
        $xmlElement->addChild($this->cleanXmlTagName($entity), $handleValue($value));
    }
}

public function cleanXmlTagName(string $tagName)
{
    if(is_numeric($tagName[0])){
        $tagName = '_'.$tagName;
    }
    return preg_replace('/[^A-Za-z0-9.\-_]/', '_', $tagName);
}

  /**
   * @param array $array
   * @param string $openingTag
   * @param string $entity
   * @param string $nameSpace
   * @param bool $isPrefixed
   * @return \SimpleXMLElement
   */
  public function generateXmlFromArray(array $array, string $openingTag, string $entity, $nameSpace = '', $isPrefixed = false)
  {
      $xmlString = '<'.$openingTag.'></'.$openingTag.'>';
      $xml = new \SimpleXMLElement($xmlString, LIBXML_NOERROR, false, $nameSpace, $isPrefixed);
      $this->getXmlFromArray($array, $xml, $entity, true);
      return $xml;
  }

  /**
   * @param string $xml
   * @return bool
   */
  public function validateXml(string $xml)
  {
      $dom = new \DOMDocument();
      $dom->loadXML($xml);
      return $dom->validate();
  }

  public function loadXmlPathAsArray(string $xmlPath)
  {
      $xml   = simplexml_load_file($xmlPath);
      $array = json_decode(json_encode($xml), TRUE);
      return (array)$array;
  }

  /**
   * @param string $xmlString
   * @return array
   */
  public function loadXmlStringAsArray(string $xmlString)
  {
      $array = (array) @simplexml_load_string($xmlString);
      if(!$array){
          $array = (array) @json_decode($xmlString, true);
      } else{
          $array = (array)@json_decode(json_encode($array), true);
      }
      return $array;
  }

  /**
   * @param string $xmlString
   * @return \SimpleXMLElement
   */
  public function loadXmlString(string $xmlString)
  {
      return @simplexml_load_string($xmlString);
  }
}

如果您還需要支持將數組轉換為XML的屬性,則可以使用以下實現: http : //www.lalit.org/lab/convert-php-array-to-xml-with-attributes/

對於屬性支持,它要求您以特定方式構造數組。 對於沒有屬性的xml,您可以直接將任何數組傳遞給函數並獲取XML

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM