PHP로 XML 생성

PHP로 XML 생성
PHP XML 출력

1 방법 1 (echo)

<?php
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='UTF-8'?>\n";
echo "<quiz>\n";
echo "<question>대한민국의 초대 대통령은?</question>\n";
echo "<answer>이승만</answer>\n";
echo "</quiz>\n";
?>

2 방법 2 (array_xml)

<?php
function array_xml($arr, $num_prefix = "num_") {
	if(!is_array($arr)) return $arr;
	$result = '';
	foreach($arr as $key => $val) {
		$key = (is_numeric($key)? $num_prefix.$key : $key);
		$result .= '<'.$key.'>'.array_xml($val, $num_prefix).'</'.$key.'>';
	}
	return $result;
}
$xml = array( 'quiz'=> array(
	'question' => '대한민국의 초대 대통령은?',
	'answer' => '이승만'
));
header('Content-type: text/xml'); 
echo "<?xml version='1.0' encoding='UTF-8'?>\n";
echo array_xml($xml);
?>

3 방법 3 (XmlConstruct)

XMLWriter를 상속하여 간단히 만든 클래스 XmlConstruct를 사용[1]

<?php 
class XmlConstruct extends XMLWriter { 
    public function __construct($prm_rootElementName, $prm_xsltFilePath='') {
        $this->openMemory(); 
        $this->setIndent(true); 
        $this->setIndentString(' '); 
        $this->startDocument('1.0', 'UTF-8'); 
        if($prm_xsltFilePath) $this->writePi('xml-stylesheet', 'type="text/xsl" href="'.$prm_xsltFilePath.'"'); 
        $this->startElement($prm_rootElementName); 
    } 
    public function setElement($prm_elementName, $prm_ElementText) {
        $this->startElement($prm_elementName); 
        $this->text($prm_ElementText); 
        $this->endElement(); 
    } 
    public function fromArray($prm_array) {
      if(!is_array($prm_array)) return;
      foreach ($prm_array as $index => $element) {
        if(is_array($element)) {
          $this->startElement($index); 
          $this->fromArray($element); 
          $this->endElement(); 
        } 
        else $this->setElement($index, $element); 
      } 
    } 
    public function getDocument() {
        $this->endElement(); 
        $this->endDocument(); 
        return $this->outputMemory(); 
    } 
    public function output() {
        header('Content-type: text/xml'); 
        echo $this->getDocument(); 
    } 
} 
$contents = array(
    'question' => '대한민국의 초대 대통령은?',
    'answer' => '이승만'
); 
$XmlConstruct = new XmlConstruct('quiz'); 
$XmlConstruct->fromArray($contents); 
$XmlConstruct->output(); 
?>

4 같이 보기

5 주석

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}