使用php

时间:2016-07-20 13:39:35

标签: php xml domdocument

我创建xml文件的尝试已接近完成,但我有一两个障碍。

通过mysql_connect()

从数据库中提取数据
$sql = "SELECT `entity_id`,`name` FROM `table`

所需的输出是:

<?xml version="1.0" encoding="utf-8"?>
<content>
    <item>
        <id>1</id>
        <name><![CDATA[name1]]</name>
    </item>
    <item>
        <id>2</id>
        <name><![CDATA[name2]]</name>
    </item>
</content>

现在我一直试图通过DOMDocument来做到这一点,但我无法正确缩进

$doc = new DOMDocument( '1.0', 'utf-8' );
$ele = $doc->createElement( 'content' );

    while ($row = mysql_fetch_assoc($res)) {

    $ele = $doc->createElement( 'id' );
    $ele->nodeValue = $row['entity_id'];
    $doc->appendChild( $ele );

    $ele = $doc->createElement( 'name' );
    $ele->nodeValue = $row['name'];
    $doc->appendChild( $ele );

    };

$doc->appendChild( $ele );
$doc->save('MyXmlFile.xml');

但是输出:

<?xml version="1.0" encoding="utf-8"?>
    <id>1</id>
    <name>name1</name>
    <id>2</id>
    <name>name2</name>

如何将结果置于子级别? (主要问题)之后我必须弄清楚如何在文本数据周围包装CDATA标签?

1 个答案:

答案 0 :(得分:0)

是否采用XMLWriter路由来解决此问题:

$xml = new XMLWriter();

$xml->openURI('myxmlfile.xml');
$xml->startDocument('1.0', 'utf-8');
$xml->setIndent(true);
$xml->startElement('content');

while ($row = mysql_fetch_assoc($res)) {

    $xml->startElement('item');

        $xml->startElement("id");
        $xml->writeRaw("$row['entity_id']);
        $xml->endElement();

        $xml->startElement("name");
        $xml->writeCData(utf8_encode ($row['name']));
        $xml->endElement();

    $xml->endElement();
    }

$xml->endElement();

$xml->flush();