使用php格式化xml文件 [英] formatted xml file using php
本文介绍了使用php格式化xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码使用 php 创建 xml 文件
i am using following code to create xml file using php
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('alerts');
$root = $doc->appendChild($root);
$alert = $doc->createElement('alert');
$alert = $root->appendChild($alert);
$id = $doc->createElement('id');
$id_text = $doc->createTextNode($api_id);
$id->appendChild($id_text);
$alert->appendChild($id);
$msg_type = $doc->createElement('msg_type');
$msg_type_text = $doc->createTextNode(1);
$msg_type->appendChild($msg_type_text);
$alert->appendChild($msg_type);
$doc->save($filename);
它以这样的格式保存xml文件
it saves xml file well formatted like this
<?xml version="1.0"?>
<alerts>
<alert>
<id>22</id>
<msg_type>1</msg_type>
</alert>
</alerts>
但是当我使用以下代码在现有文件中附加标签时,它不会格式化
but when i append tags in existing file with following code it will not formatted
$doc = new DOMDocument();
$doc->formatOutput = true;
$xml = file_get_contents($filename);
$doc->loadXML($xml);
$root = $doc->firstChild;
$alert = $doc->createElement('alert');
$alert = $root->appendChild($alert);
$id = $doc->createElement('id');
$id_text = $doc->createTextNode($api_id);
$id->appendChild($id_text);
$alert->appendChild($id);
$msg_type = $doc->createElement('msg_type');
$msg_type_text = $doc->createTextNode(1);
$msg_type->appendChild($msg_type_text);
$alert->appendChild($msg_type);
$doc->save($filename);
xml 文件格式是这样的
xml file format will be like this
<alerts>
<alert>
<id>3</id>
<msg_type>1</msg_type>
<msg>Api Name:Loop LM (H-PO) has low credit.</msg>
<url>common/api/view_sms_api_list.php</url>
<status>0</status>
<create_date>1387351877</create_date>
</alert>
<alert><id>6</id><msg_type>1</msg_type></alert><alert><id>14</id><msg_type>1</msg_type></alert><alert><id>24</id><msg_type>1</msg_type></alert></alerts>
当我在这个 xml 文件中附加一个警报标签时,它将继续单行.问题是什么?提前致谢.
it will continue in single line when i append a alert tag in this xml file. what is the problem? thanks in advance.
推荐答案
在加载你的文档之前添加 $doc->preserveWhiteSpace = false;
$doc->loadXML($xml);
Add $doc->preserveWhiteSpace = false;
before load your doc $doc->loadXML($xml);
这篇关于使用php格式化xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文