php教程 PHP源码 PHP에서 XML 파일을 생성하는 4가지 방법

PHP에서 XML 파일을 생성하는 4가지 방법

Nov 09, 2016 am 10:06 AM

PHP에서 XML 파일을 생성하는 4가지 방법

<?xml version="1.0" encoding="utf-8"?>
<article>
    <item>
        <title size="1">title1</title>
        <content>content1</content>
        <pubdate>2009-10-11</pubdate>
    </item>
    <item>
        <title size="1">title2</title>
        <content>content2</content>
        <pubdate>2009-11-11</pubdate>
    </item>
</article>
로그인 후 복사

[문자열 직접 생성]
방법 1: 순수 PHP 코드를 사용하여 문자열을 생성하고 이 문자열을 접미사로 XML이 있는 파일입니다. 이는 XML을 생성하는 가장 원시적인 방법이지만 작동합니다!
PHP 코드는 다음과 같습니다.

<?PHP
$data_array = array(
    array(
    &#39;title&#39; => &#39;title1&#39;,
    &#39;content&#39; => &#39;content1&#39;,
        &#39;pubdate&#39; => &#39;2009-10-11&#39;,
    ),
    array(
    &#39;title&#39; => &#39;title2&#39;,
    &#39;content&#39; => &#39;content2&#39;,
    &#39;pubdate&#39; => &#39;2009-11-11&#39;,
    )
);
$title_size = 1;
 
$xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xml .= "<article>\n";
 
foreach ($data_array as $data) {
$xml .= create_item($data[&#39;title&#39;], $title_size, $data[&#39;content&#39;], $data[&#39;pubdate&#39;]);
}
 
$xml .= "</article>\n";
 
echo $xml;
 
//  创建XML单项
function create_item($title_data, $title_size, $content_data, $pubdate_data)
{
    $item = "<item>\n";
    $item .= "<title size=\"" . $title_size . "\">" . $title_data . "</title>\n";
    $item .= "<content>" . $content_data . "</content>\n";
    $item .= " <pubdate>" . $pubdate_data . "</pubdate>\n";
    $item .= "</item>\n";
 
    return $item;
}
 
?>
로그인 후 복사

【DomDocument】
방법 2: DomDocument를 사용하여 XML 파일 생성
createElement 메서드를 사용하여 노드를 생성합니다.
텍스트 생성 콘텐츠는 createTextNode 메서드를 사용하고,
은appendChild 메서드를 사용하여 하위 노드를 추가하고,
는 createAttribute 메서드를 사용하여 속성을 생성합니다.
PHP 코드는 다음과 같습니다.

<?PHP
$data_array = array(
    array(
    &#39;title&#39; => &#39;title1&#39;,
    &#39;content&#39; => &#39;content1&#39;,
        &#39;pubdate&#39; => &#39;2009-10-11&#39;,
    ),
    array(
    &#39;title&#39; => &#39;title2&#39;,
    &#39;content&#39; => &#39;content2&#39;,
    &#39;pubdate&#39; => &#39;2009-11-11&#39;,
    )
);
 
//  属性数组
$attribute_array = array(
    &#39;title&#39; => array(
    &#39;size&#39; => 1
    )
);
 
//  创建一个XML文档并设置XML版本和编码。。
$dom=new DomDocument(&#39;1.0&#39;, &#39;utf-8&#39;);
 
//  创建根节点
$article = $dom->createElement(&#39;article&#39;);
$dom->appendchild($article);
 
foreach ($data_array as $data) {
    $item = $dom->createElement(&#39;item&#39;);
    $article->appendchild($item);
 
    create_item($dom, $item, $data, $attribute_array);
}
 
echo $dom->saveXML();
 
function create_item($dom, $item, $data, $attribute) {
    if (is_array($data)) {
        foreach ($data as $key => $val) {
            //  创建元素
            $$key = $dom->createElement($key);
            $item->appendchild($$key);
 
            //  创建元素值
            $text = $dom->createTextNode($val);
            $$key->appendchild($text);
 
            if (isset($attribute[$key])) {
            //  如果此字段存在相关属性需要设置
                foreach ($attribute[$key] as $akey => $row) {
                    //  创建属性节点
                    $$akey = $dom->createAttribute($akey);
                    $$key->appendchild($$akey);
 
                    // 创建属性值节点
                    $aval = $dom->createTextNode($row);
                    $$akey->appendChild($aval);
                }
            }   //  end if
        }
    }   //  end if
}   //  end function
?>
로그인 후 복사

[XMLWriter]
방법 3: XMLWriter 클래스를 사용하여 XML 파일 생성
이 방법은 PHP 5.1.2 이후에 유효합니다.
또한 XML의 여러 인코딩을 출력할 수 있지만, 입력은 utf-8만 가능합니다
PHP 코드는 다음과 같습니다:

<?PHP
$data_array = array(
    array(
    &#39;title&#39; => &#39;title1&#39;,
    &#39;content&#39; => &#39;content1&#39;,
        &#39;pubdate&#39; => &#39;2009-10-11&#39;,
    ),
    array(
    &#39;title&#39; => &#39;title2&#39;,
    &#39;content&#39; => &#39;content2&#39;,
    &#39;pubdate&#39; => &#39;2009-11-11&#39;,
    )
);
 
//  属性数组
$attribute_array = array(
    &#39;title&#39; => array(
    &#39;size&#39; => 1
    )
);
 
$xml = new XMLWriter();
$xml->openUri("php://output");
//  输出方式,也可以设置为某个xml文件地址,直接输出成文件
$xml->setIndentString(&#39;  &#39;);
$xml->setIndent(true);
 
$xml->startDocument(&#39;1.0&#39;, &#39;utf-8&#39;);
//  开始创建文件
//  根结点
$xml->startElement(&#39;article&#39;);
 
foreach ($data_array as $data) {
    $xml->startElement(&#39;item&#39;);
 
    if (is_array($data)) {
        foreach ($data as $key => $row) {
          $xml->startElement($key);
 
          if (isset($attribute_array[$key]) && is_array($attribute_array[$key]))
          {
              foreach ($attribute_array[$key] as $akey => $aval) {
              //  设置属性值
                    $xml->writeAttribute($akey, $aval);
                }
 
            }
 
            $xml->text($row);   //  设置内容
            $xml->endElement(); // $key
        }
 
    }
    $xml->endElement(); //  item
}
 
$xml->endElement(); //  article
$xml->endDocument();
 
$xml->flush();
?>
로그인 후 복사

【SimpleXML】
방법 4: SimpleXML을 사용하여 XML 문서 만들기

<?PHP
$data_array = array(
    array(
    &#39;title&#39; => &#39;title1&#39;,
    &#39;content&#39; => &#39;content1&#39;,
        &#39;pubdate&#39; => &#39;2009-10-11&#39;,
    ),
    array(
    &#39;title&#39; => &#39;title2&#39;,
    &#39;content&#39; => &#39;content2&#39;,
    &#39;pubdate&#39; => &#39;2009-11-11&#39;,
    )
);
 
//  属性数组
$attribute_array = array(
    &#39;title&#39; => array(
    &#39;size&#39; => 1
    )
);
 
$string = <<<XML
<?xml version=&#39;1.0&#39; encoding=&#39;utf-8&#39;?>
<article>
</article>
XML;
 
$xml = simplexml_load_string($string);
 
foreach ($data_array as $data) {
    $item = $xml->addChild(&#39;item&#39;);
    if (is_array($data)) {
        foreach ($data as $key => $row) {
          $node = $item->addChild($key, $row);
 
          if (isset($attribute_array[$key]) && is_array($attribute_array[$key]))
            {
              foreach ($attribute_array[$key] as $akey => $aval) {
             //  设置属性值
                  $node->addAttribute($akey, $aval);
            }
          }
        }
    }
}
echo $xml->asXML();
?>
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)