我对 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!";
}
}
}
?>
谢谢!