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



我有一个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->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!";
}
    }
}
?>

谢谢!

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

所以例如下面的结构:

lib
   xmlClientMappers.php
   client.xml
index.php

你必须使用"./lib/client.xml"作为你的文件名。

相关内容

  • 没有找到相关文章

最新更新