0

我有一个这样的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->numberandecho $x->name为空白且 if 为假。

    $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);
    }
}
4

1 回答 1

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();
于 2013-10-01T16:38:09.167 回答