2 回答
TA贡献1818条经验 获得超11个赞
尝试这个:
<?php
if(isset($_POST['submitSave'])){
$products = new DOMDocument('1.0');
$products->preserveWhiteSpace = false;
$products->formatOutput = true;
// $doc->load('data/product.xml');
$product = $products->createElement('product');
$product->setAttribute('id', $_POST['id']);
$name = $products->createElement('name', $_POST['name']);
$price = $products->createElement('price', $_POST['price']);
$products->appendChild($product);
$product->appendChild($name);
$product->appendChild($price);
file_put_contents('data/product.xml', $products->saveXML());
// echo $products->saveXML();
}
?>
这是没有 POST 参数的ideone上的演示
这是我在本地机器上的输出,使用后置参数
编辑:这里要求的是保留旧数据的代码
<?php
if(isset($_POST['submitSave'])){
// Disable errors due to empty xml files
error_reporting(E_ALL & ~E_WARNING);
$domDoc = new DOMDocument('1.0');
$domDoc->preserveWhiteSpace = false;
$domDoc->formatOutput = true;
// load xml file
try {
$domDoc->load('./data/product.xml');
} catch (\Throwable $th) {
//throw $th;
}
if($domDoc->getElementsByTagName('products')->length>0){
// If we already have products tag defined
$products = $domDoc->getElementsByTagName('products')[0];
}else{
// If we don't have any products tag, i.e. file is empty
$products = $domDoc->createElement('products');
}
// Create child node for product and set id(attribute), name(child), price(child)
$product = $domDoc->createElement('product');
$product->setAttribute('id', $_POST['id']);
$name = $domDoc->createElement('name', $_POST['name']);
$price = $domDoc->createElement('price', $_POST['price']);
$domDoc->appendChild($products);
$products->appendChild($product);
$product->appendChild($name);
$product->appendChild($price);
file_put_contents('./data/product.xml', $domDoc->saveXML());
}
?>
这是我本地机器上的输出:
TA贡献2051条经验 获得超10个赞
输出文件是 product.xml。对于测试,我使用http://localhost/teste.php?id=p02&name=Name2&price=200¤cy=USD
$xmlstr= "<products></products>";
$sxe = new SimpleXMLElement($xmlstr);
$product = $sxe->addChild('product');
$product->addAttribute('id', $_REQUEST['id']);
$product->addChild('name', $_REQUEST['name']);
$price = $product->addChild('price', $_REQUEST['price']);
$price->addAttribute('currency', $_REQUEST['currency']);
$xmlOutput = $sxe->asXML();
file_put_contents('product.xml',$xmlOutput);
- 2 回答
- 0 关注
- 125 浏览
添加回答
举报