我有一个像这样的xml文件:
<participants>
<participant>
<number>1</number>
<name>toto</name>
</participant>
<participant>
<number>2</number>
<name>titi</titi>
</participant>
<participant>
<number>3</number>
<name>tata</titi>
</participant>
</participants>
我有一些参与者,并希望直接访问节点以更新或删除它。
问题是$x
不正确,因为echo $x->number
且echo $x->name
为空,而if为false。
$x = $participant->item($number);
echo 'number = '.$x->number;
echo 'name = '.$x->name;
请帮忙。感谢。
$number=2;
if ($xml = file_get_contents($file))
{
$xmldoc = new DOMDocument('1.0', 'utf-8');
$xmldoc->loadXML($xml, LIBXML_NOBLANKS);
// find the participants tag
$root = $xmldoc->getElementsByTagName('participants')->item(0);
// get the list of participant node
$participant = $xmldoc->getElementsByTagName('participant') ;
echo $participant->length; // I have a good number of participant node
// get the node with the number i want
$x = $participant->item($number);
echo 'number = '.$x->number;
echo 'name = '.$x->name;
if ($x->number == $number) {
echo "remove";
$participant.removeChild($x);
}
}
答案 0 :(得分:0)
这对我有用。
<?php
$number=2;
if ($xml = file_get_contents("a.xml"))
{
$xmldoc = new DOMDocument('1.0', 'utf-8');
$xmldoc->loadXML($xml, LIBXML_NOBLANKS);
// find the participants tag
$root = $xmldoc->getElementsByTagName('participants')->item(0);
// get the list of participant node
$participant = $xmldoc->getElementsByTagName('participant');
$participant->length; // I have a good number of participant node
// get the node with the number i want
$name_get = $participant->item($number-1)->getElementsByTagName('number')->item(0)->nodeValue;
$number_get = $participant->item($number-1)->getElementsByTagName('number')->item(0)->nodeValue;
echo 'number = '.$name_get;
echo 'name = '.$number_get;
if ($number_get == $number) {
echo "remove";
$removing_node = $participant->item($number_get-1);
$root->removeChild($removing_node);
}
}
echo $xmldoc->saveXML();