我必须在运行时动态生成一个xml文件。请帮助我用PHP动态生成下面的XML文件。
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<track>
<path>song1.mp3</path>
<title>Track 1 - Track Title</title>
</track>
<track>
<path>song2.mp3</path>
<title>Track 2 - Track Title</title>
</track>
<track>
<path>song3.mp3</path>
<title>Track 3 - Track Title</title>
</track>
<track>
<path>song4.mp3</path>
<title>Track 4 - Track Title</title>
</track>
<track>
<path>song5.mp3</path>
<title>Track 5 - Track Title</title>
</track>
<track>
<path>song6.mp3</path>
<title>Track 6 - Track Title</title>
</track>
<track>
<path>song7.mp3</path>
<title>Track 7 - Track Title</title>
</track>
<track>
<path>song8.mp3</path>
<title>Track 8 - Track Title</title>
</track>
希望这段代码可以帮助你。简单易行的解决方案
$dom = new DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
$xml_file_name = './movies_list.xml'; //You can give your path to save file.
$root = $dom->createElement('Movies');
$movie_node = $dom->createElement('movie');
$attr_movie_id = new DOMAttr('movie_id', '5467');
$movie_node->setAttributeNode($attr_movie_id);
$child_node_title = $dom->createElement('Title', 'The Campaign');
$movie_node->appendChild($child_node_title);
$child_node_year = $dom->createElement('Year', 2012);
$movie_node->appendChild($child_node_year);
$child_node_genre = $dom->createElement('Genre', 'The Campaign');
$movie_node->appendChild($child_node_genre);
$child_node_ratings = $dom->createElement('Ratings', 6.2);
$movie_node->appendChild($child_node_ratings);
$root->appendChild($movie_node);
$dom->appendChild($root);
$dom->save($xml_file_name);
欲了解更多信息,请访问https://www.guru99.com/php-and-xml.html以获取详细信息
我看到了DOM和SimpleXML的例子,但没有一个使用XMLWriter的例子。
请记住,从我所做的测试来看,DOM和SimpleXML几乎都比XMLWriter慢了一倍,对于较大的文件,您应该考虑使用后者。
下面是一个完整的工作示例,清晰而简单,符合要求,用XMLWriter编写(我相信它会帮助其他用户):
// array with the key / value pairs of the information to be added (can be an array with the data fetched from db as well)
$songs = [
'song1.mp3' => 'Track 1 - Track Title',
'song2.mp3' => 'Track 2 - Track Title',
'song3.mp3' => 'Track 3 - Track Title',
'song4.mp3' => 'Track 4 - Track Title',
'song5.mp3' => 'Track 5 - Track Title',
'song6.mp3' => 'Track 6 - Track Title',
'song7.mp3' => 'Track 7 - Track Title',
'song8.mp3' => 'Track 8 - Track Title',
];
$xml = new XMLWriter();
$xml->openURI('songs.xml');
$xml->setIndent(true);
$xml->setIndentString(' ');
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('xml');
foreach($songs as $song => $track){
$xml->startElement('track');
$xml->writeElement('path', $song);
$xml->writeElement('title', $track);
$xml->endElement();
}
$xml->endElement();
$xml->endDocument();
$xml->flush();
unset($xml);