我有一个包含许多元素的xml文件,我希望根据它们的索引删除某些元素。
示例XML:
<songs>
<song>
<title>A</title>
<artist>AA</artist>
</song>
</songs>
我到目前为止的PHP代码:
<?php
$index = $_GET['song'];
$doc = new DOMDocument();
$doc->load("songs.xml");
$songs = $doc->getElementsByTagName("song");
foreach($songs as $song) {
if(in_array($song[$index], $songs)){
unset($song);
}
}
$doc->save("songlist.xml");
?>
但是我从这段代码中得到了这个错误:
Fatal error: Cannot use object of type DOMElement as array
本期内有任何帮助,谢谢。
答案 0 :(得分:1)
如果您打算删除整个<song>
元素。使用->removeChild()
:
$songs = $doc->getElementsByTagName('song');
$hated_artists = array('AA', 'BB', 'CC');
foreach($songs as $song) {
$artist = $song->getElementsByTagName('artist')->item(0)->nodeValue;
if(in_array($artist, $hated_artists)) { // if this song is sang by one of your hated artists
$song->parentNode->removeChild($song); // remove this song
}
}
如果您只想要一个简单的条件,请使用所需的密钥删除,然后只需使用foreach
密钥即可。例如:
$keys_to_be_removed = array(14, 18);
foreach($songs as $key => $song) {
if(in_array($key, $keys_to_be_removed)) {
$song->parentNode->removeChild($song);
}
}
或者只是在没有foreach循环的情况下明确使用索引来删除:
// starts at index zero
$first_song = $doc->getElementsByTagName('song')->item(0);
$songs = $doc->documentElement;
$songs->removeChild($first_song);
答案 1 :(得分:0)
$songs = $doc->getElementsByTagName('song');
$songs.item(1).parentNode.removeChild($songs.item(1));
$songs.item(7).parentNode.removeChild($songs.item(7));
$songs.item(12).parentNode.removeChild($songs.item(12));
等...
答案 2 :(得分:0)
XPath可以按索引/位置选择节点(以1开头)。它将始终返回可与foreach遍历的节点列表。如果索引不存在,列表将为空。要从DOM中删除节点,必须将其从父节点中删除。
$xml = <<<'XML'
<songs>
<song>
<title>A</title>
<artist>AA</artist>
</song>
</songs>
XML;
$index = 1; // (int)$_GET['song'];
$doc = new DOMDocument();
$doc->loadXml($xml);
$xpath = new DOMXPath($doc);
foreach ($xpath->evaluate('//song['.$index.']') as $song) {
$song->parentNode->removeChild($song);
}
echo $doc->saveXml();
输出:
<?xml version="1.0"?>
<songs>
</songs>