基本上,当我尝试使用 php 将 RSS 提要中的多个项目添加到 XML 文件时,insertBefore 类会以错误的方式添加最新的项目(即,我希望它从最旧的开始将它们添加到文件的顶部到最新,而是将它们从最新到最旧添加)我该如何解决这个问题?(抱歉措辞糟糕)这是我的代码:
$dom = new DOMDocument;
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->load(myfile);
$channel = $dom->getElementsByTagName('channel');
foreach ($channel as $channels) {
$item1 = $dom->createElement('item');
$item2 = $dom->createElement('item');
$item3 = $dom->createElement('item');
$title1 = $dom->createElement('title', $t1);
$title2 = $dom->createElement('title', $t2);
$title3 = $dom->createElement('title', $t3);
$content1 = $dom->createElement('media:content');
$conatt1 = $dom->createAttribute('url');
$content2 = $dom->createElement('media:content');
$conatt2 = $dom->createAttribute('url');
$content3 = $dom->createElement('media:content');
$conatt3 = $dom->createAttribute('url');
$conatt1->value = $u1;
$conatt2->value = $u2;
$conatt3->value = $u3;
$channels->insertBefore($item1, $channels->firstChild);
$channels->insertBefore($item2, $channels->firstChild);
$channels->insertBefore($item3, $channels->firstChild);
$item1->appendChild($title1);
$item2->appendChild($title2);
$item3->appendChild($title3);
$item1->appendChild($content1);
$item2->appendChild($content2);
$item3->appendChild($content3);
$content1->appendChild($conatt1);
$content2->appendChild($conatt2);
$content3->appendChild($conatt3);
}
以及它生成的 XML=
<channel>
<item>
<title>item3</title>
<media:content url="url3"/>
</item>
<item>
<title>item2</title>
<media:content url="url2"/>
</item>
<item>
<title>item1</title>
<media:content url="url"/>
</item>
//rest of the RSS
</channel>
但我想要它,所以它添加了这样的项目:
<channel>
<item>
<title>item1</title>
<media:content url="url1"/>
</item>
<item>
<title>item2</title>
<media:content url="url2"/>
</item>
<item>
<title>item3</title>
<media:content url="url3"/>
</item>
//rest of the RSS
</channel>
任何建议(再次,对于糟糕的解释感到抱歉)
编辑
这是我的其他代码,我该怎么做呢?
$fom = new DOMDocument;
$fom->formatOutput = true;
$fom->preserveWhiteSpace = false;
$fom->load("file");
$channel = $fom->getElementsByTagName('channel');
foreach ($channel as $channels) {
$item1 = $fom->createElement('item');
$title1 = $fom->createElement('title', $titles[$i]);
$content1 = $fom->createElement('media:content');
$conatt1 = $fom->createAttribute('url');
$conatt1->value = $links[$i];
$channels->insertBefore($item1, $channels->firstChild);
$item1->appendChild($title1);
$item1->appendChild($content1);
$content1->appendChild($conatt1);
$fom->formatOutput = true;
$fom->preserveWhiteSpace = false;
$fom->save("file");
}
}