我必须在运行时动态生成一个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和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);