>  기사  >  백엔드 개발  >  배열을 XML_php 팁으로 변환하는 PHP 방법

배열을 XML_php 팁으로 변환하는 PHP 방법

WBOY
WBOY원래의
2016-05-16 20:21:35866검색

이 기사의 예에서는 PHP에서 배열을 XML로 변환하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 내용은 다음과 같습니다.

1. PHP 코드는 다음과 같습니다.

<&#63;php
class A2Xml {
  private $version  = '1.0';
  private $encoding  = 'UTF-8';
  private $root    = 'root';
  private $xml    = null;
  function __construct() {
    $this->xml = new XmlWriter();
  }
  function toXml($data, $eIsArray=FALSE) {
    if(!$eIsArray) {
      $this->xml->openMemory();
      $this->xml->startDocument($this->version, $this->encoding);
      $this->xml->startElement($this->root);
    }
    foreach($data as $key => $value){
 
      if(is_array($value)){
        $this->xml->startElement($key);
        $this->toXml($value, TRUE);
        $this->xml->endElement();
        continue;
      }
      $this->xml->writeElement($key, $value);
    }
    if(!$eIsArray) {
      $this->xml->endElement();
      return $this->xml->outputMemory(true);
    }
  }
}
$res = array(
  'hello' => '11212',
  'world' => '232323',
  'array' => array(
    'test' => 'test',
    'b'  => array('c'=>'c', 'd'=>'d')
  ),
  'a' => 'haha'
);
$xml = new A2Xml();
echo $xml->toXml($res);

2. 작업 효과는 아래 그림과 같습니다.

이 기사가 모든 사람의 PHP 프로그래밍 설계에 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.