我创建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标签?
答案 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();