首页 > 解决方案 > 为树中的输出文件格式化 XML 不起作用

问题描述

我尝试以多种方式使用 php 代码以树格式保存到 xml 文件,但没有成功。有什么不对劲,我不知道。输出格式仍然是一个长字符串,如下所示:

<products><product id="p02"><name>Name 2</name><price currency="USD">200</price></product></products>

我需要帮助。这是我的代码:

  <?php
  if(isset($_POST['submitSave'])) {
    $products = new DOMDocument('1.0');
    $products->preserveWhiteSpace = false;
    $products->formatOutput = true;
$doc->load('data/product.xml');
$product = $products->addChild('product');
$product->addAttribute('id', $_POST['id']);
$product->addChild('name', $_POST['name']);
$product->addChild('price', $_POST['price']);
file_put_contents('data/product.xml', $doc->saveXML());
header('location:index.php');
}
?>

标签: javascriptphphtmlxmlforms

解决方案


输出文件是 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);

推荐阅读