将PHP数组转换为XML?

3

假设我有一个像这样的数组:

<?php
$colors=array();

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


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

......
?>

什么是将整个数组转换为XML的最简单方法?
4个回答

0

我花了很多小时才做到这一点。我真的不敢相信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 = new Xml(); $xml->generateXmlFromArray($array, 'entities', 'entity'); - kurtbr

0

0

1
第一个链接没有回答问题,第二个链接已经失效。请检查您的回答。我还添加了一个额外的链接,其中包含了一个类似问题的答案。 - hakre

0
你可以创建一个简单的函数来输出它。例如,将包含元素的数组传递给函数,并告诉父元素(文档的根元素)和每个元素的名称。
我假设父元素为“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>

如果您有更加复杂的嵌套数组结构,您可能想以递归的方式解决它。一些相关的问题:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接