使用php将元素添加到xml文件中

时间:2013-04-24 09:08:24

标签: php xml oop netbeans

我有php和xml文件的问题:我想在xml文件中添加一个元素。我写了这段代码并且有效:

<?php

$file = 'clients.xml';                

$doc = new DOMDocument();                 
$doc->load($file);                       
$get_elms = $doc->getElementsByTagName("Client");     
$nr_elms = $get_elms->length;             

$node = $get_elms->item($nr_elms-1);              
$element = $node->nodeName;               

if($element=='Client') {
    $idfinal=intval($node->getAttribute('id'))+1;
    $client = $doc->createElement('Client');                          
    $node->parentNode->appendChild($client);   
    $client->setAttribute('id',$idfinal);    
    $client->setAttribute('name','Any name');
    $client->setAttribute('cnp','12345');
    $client->setAttribute('adress','adress');
    $client->setAttribute('nb','123');
    $client->setAttribute('amount','1000');
    $client->setAttribute('type','Any type');

 }


if($doc->save('clients.xml')) {
echo htmlentities($doc->saveXML());
}


?>

如果我将完全相同的代码放入类中,则在函数addClient中它不起作用,因为它无法识别我的xml文件。我试过echo $ get_elms-&gt; length;并且它返回0并且我的变量$ element为空,因此它不会输入“if”。我需要使用这个类,因为我必须做更多的操作,如删除和更新,我必须向这些函数发送一些参数。谁能帮助我,告诉我我做错了什么?

我的班级看起来像这样:

class xmlClientMappers {


    public function adaugaClient(array $row)
    {

        $name    = $row['name'];
        $adress  = $row['adress'];
        $cnp     = $row['cnp'];
        $nb      = $row['nb'];
        $amount  = $row['amount'];
        $type    = $row['type'];

      $file = 'clients.xml';                

$doc = new DOMDocument();                 
$doc->load($file);                       
$get_elms = $doc->getElementsByTagName("*");     
$nr_elms = $get_elms->length;             
echo "The nomber is ".$nr_elms;
$node = $get_elms->item($nr_elms-1);              
$element = $node->nodeName;               
echo "<br/>Here should be the name of the last element".$element;
if($element=='Client') {
    $idfinal=intval($node->getAttribute('id'))+1;
    echo " id-ul e ".$idfinal;
    $client = $doc->createElement('Client');                          
    $node->parentNode->appendChild($client);   
    $client->setAttribute('id',$idfinal);    
    $client->setAttribute('name',$name);
    $client->setAttribute('cnp',$cnp);
    $client->setAttribute('adress',$adress);
    $client->setAttribute('nb',$nb);
    $client->setAttribute('amount',$amount);
    $client->setAttribute('type',$type);

}


     if($doc->save('clienti.xml')) {
       echo htmlentities($doc->saveXML());
  else echo "It is wrong!";
}
    }
}
?>

谢谢!

1 个答案:

答案 0 :(得分:0)

您必须将xml位置相对于执行请求的文件的位置。

所以例如以下结构:

lib
  \ xmlClientMappers.php
  \ client.xml
index.php

你必须使用&#34; ./ lib / client.xml&#34;为你的文件名。

我认为这将是问题所在。