1.xml内容:<?xml version="1.0" encoding="utf-8" ?>
- <root>
- <product id="1">
<price>0.19</price>
<username>达菲鸡</username>
</product>
</root>
1.php内容:$file = '1.xml';
$doc = new DomDocument('1.0', 'utf-8');
$doc->load($file);
$xml = $doc->saveXML();
$product = $doc->getElementById('1');
$pricenew = $doc->getElementsByTagName('price');
var_dump($product);
var_dump($product);的结果为null,而var_dump($pricenew);的结果为object(DOMNodeList)#2 (0) { }。
问:为什么为空呢?读取到price元素后要怎么才能把0.19修改成1.19呢?
- <root>
- <product id="1">
<price>0.19</price>
<username>达菲鸡</username>
</product>
</root>
1.php内容:$file = '1.xml';
$doc = new DomDocument('1.0', 'utf-8');
$doc->load($file);
$xml = $doc->saveXML();
$product = $doc->getElementById('1');
$pricenew = $doc->getElementsByTagName('price');
var_dump($product);
var_dump($product);的结果为null,而var_dump($pricenew);的结果为object(DOMNodeList)#2 (0) { }。
问:为什么为空呢?读取到price元素后要怎么才能把0.19修改成1.19呢?
参考手册上的说明
http://www.php.net/manual/en/function.domdocument-get-element-by-id.phpprice的值用nodeValue来取和变更
$pricenew = $doc->getElementsByTagName('price')->item(0);
echo $pricenew->nodeValue;
$pricenew->nodeValue = 1.19
e文不太好,写了几行生成xml的代码,帮看下是不是这样用?function create($productID, $price, $username){
$file = '1.xml';
$doc = new DomDocument('1.0', 'utf-8');
$root = $doc->appendchild($doc->createElement('root'));
$product = $root->appendchild($doc->createElement('product'));
$product->setAttribute('id',$productID);
$product->setIdAttribute('id',true);
$product->appendchild($doc->createElement('price',$price));
$product->appendchild($doc->createElement('username',$username));
$new = $doc->save($file);
return $new;
}
$product = $doc->getElementById('1');
var_dump($product);的结果依然为null