我是PHP新手,我想使用PHP编辑XML文件。当我在我的xml文件中添加child时,我没有以正确的格式化方式获取它们。这是在文件中进一步编辑时创建故障日志。请帮我编辑我的xml文件,以便生成的xml格式正确。
提前致谢。
我正在使用此代码编辑我的xml文件
<?php
$xml_file = simplexml_load_file('editing.xml');
$xml_file->formatOutput = true;
$xml_file->preserveWhiteSpace = false;
$xml_file->addChild('article',' ')->addAttribute('id', 'id3');
file_put_contents('editing.xml', $xml_file->asXML());
?>
这是我正在使用的xml文件。
<?xml version="1.0" encoding="utf-8"?>
<userva>
<user id="BPL000001" first_name="f_name" last_name="l_name">
<article id="wersomething">
<title>Some title</title>
<description>he does play well all the time</description>
<posted_on>11/Nov/2012</posted_on>
<text_contents>Some contents.. Some Contents..Some contents.. Some Contents..Some contents.. Some Contents..</text_contents>
<images>
<image>image1.jpg</image>
<image>image2.jpg</image>
</images>
<links>
<link>link1</link>
<link>link2</link>
</links>
<likes>
<like>like11</like>
<like>like12</like>
<like>like13</like>
<like>like14</like>
<like>like15</like>
</likes>
<comments>
<comment by="523423440"/>
<comment by="054232130"/>
<comment by="15849584200"/>
</comments>
</article>
<article id="id2">
<title>Some title</title>
<description>he does play well all the time</description>
<posted_on>95956262</posted_on>
<text_contents>Some contents.. Some Contents..Some contents.. Some Contents..Some contents.. Some Contents..</text_contents>
<images>
<image>imageva1.jpg</image>
<image>imageva2.jpg</image>
</images>
<links>
<link>link1</link>
<link>link2</link>
</links>
<likes>
<like>like21</like>
<like>like22</like>
<like>like23</like>
<like>like24</like>
<like>like25</like>
</likes>
<comments>
<comment by="0142264340"/>
<comment by="0523412130"/>
<comment by="5523484200"/>
</comments>
</article>
</user>
</userva>
答案 0 :(得分:1)
参考此
http://php.net/manual/en/function.simplexml-element-asXML.php
试试这个:
$dom = dom_import_simplexml($simpleXml)->ownerDocument;
$dom->formatOutput = true;
echo $dom->saveXML();