如何使用 PHP 保存 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3552755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:12:05 来源:igfitidea点击:
How to save XML using PHP
提问by Malcolm
Anyone know how I can create and save XML using PHP? I need something like this:
任何人都知道如何使用 PHP 创建和保存 XML?我需要这样的东西:
<jukebox>
<track source="" artist="" album="" title="" />
<track source="" artist="" album="" title="" />
<track source="" artist="" album="" title="" />
<track source="" artist="" album="" title="" />
</jukebox>
回答by vfn
This is probably what you are looking for.
这可能就是您正在寻找的。
//Creates XML string and XML document using the DOM
$dom = new DomDocument('1.0', 'UTF-8');
//add root
$root = $dom->appendChild($dom->createElement('Root'));
//add NodeA element to Root
$nodeA = $dom->createElement('NodeA');
$root->appendChild($nodeA);
// Appending attr1 and attr2 to the NodeA element
$attr = $dom->createAttribute('attr1');
$attr->appendChild($dom->createTextNode('some text'));
$nodeA->appendChild($attr);
/*
** insert more nodes
*/
$dom->formatOutput = true; // set the formatOutput attribute of domDocument to true
// save XML as string or file
$test1 = $dom->saveXML(); // put string in test1
$dom->save('test1.xml'); // save as file
For more information, have a look at the DOM Documentation.
有关更多信息,请查看DOM 文档。
To do what you want:
做你想做的事:
//Creates XML string and XML document using the DOM
$dom = new DomDocument('1.0', 'UTF-8');
//add root == jukebox
$jukebox = $dom->appendChild($dom->createElement('jukebox'));
for ($i = 0; $i < count($arrayWithTracks); $i++) {
//add track element to jukebox
$track = $dom->createElement('track');
$jukebox->appendChild($track);
// Appending attributes to track
$attr = $dom->createAttribute('source');
$attr->appendChild($dom->createTextNode($arrayWithTracks[$i]['source']));
$track->appendChild($attr);
$attr = $dom->createAttribute('artist');
$attr->appendChild($dom->createTextNode($arrayWithTracks[$i]['artist']));
$track->appendChild($attr);
$attr = $dom->createAttribute('album');
$attr->appendChild($dom->createTextNode($arrayWithTracks[$i]['album']));
$track->appendChild($attr);
$attr = $dom->createAttribute('title');
$attr->appendChild($dom->createTextNode($arrayWithTracks[$i]['title']));
$track->appendChild($attr);
}
$dom->formatOutput = true; // set the formatOutput attribute of domDocument to true
// save XML as string or file
$test1 = $dom->saveXML(); // put string in test1
$dom->save('test1.xml'); // save as file
Cheers
干杯