javascript - 为树中的输出文件格式化 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');
}
?>
解决方案
输出文件是 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);
推荐阅读
- html - Edge 中带有不必要的垂直滚动条的页面
- java - swt 菜单上单击隐藏显示复合
- azure-resource-manager - 429错误时如何在Azure帐户中增加读取次数请求限制
- sql - 在包含顶级 UNION INTERSECT 或 EXCEPT 运算符的语句中不允许变量赋值
- pandas-groupby - pandas groupby 提取前百分比 n 数据(降序)
- android - 在颤振应用程序中获得互联网许可
- tcp - 尝试通过 AT 命令连接到 4G GSM 模块时 TCP/IP 连接被拒绝
- c# - 如何在 C# 中反序列化这个 xml 数据?
- javascript - Node.js 中未使用 RS256 算法生成 jsonwebtoken 令牌
- reactjs - StripeCheckout - 如何将附加数据传递给 handleToken 函数?