问题描述
<?php
if (isset($_POST['submitProduct']))
{
$xml = new DomDocument("1.0","UTF-8");
$xml->load('./data/productDB.xml');
$productName = $_POST['productName'];
$productDescription = $_POST['productDescription'];
$quantity = $_POST['quantity'];
$stock = $_POST['stock'];
$price = $_POST['price'];
$size = $_POST['size'];
$type = $_POST['type'];
$rootTag = $xml->getElementsByTagName("root")->item(0);
$infoTag = $xml->createElement("info");
$productNameTag = $xml->createElement("product-name",$productName);
$productDescriptionTag = $xml->createElement("product-description",$productDescription);
$quantityTag = $xml->createElement("quantity",$quantity);
$stockTag = $xml->createElement("stock",$stock);
$priceTag = $xml->createElement("price",$price);
$infoTag->append($productNameTag);
$infoTag->append($productDescriptionTag);
$infoTag->append($quantityTag);
$infoTag->append($stockTag);
$infoTag->append($priceTag);
$rootTag->append($infoTag);
$xml->save("productDB.xml");
}
?>
在这里,我有$ size和$ type这两个数组。但是,如果我使用以下方法将这些数组添加到xml中:
$sizeTag = $xml->createElement("size",$size);
我收到以下错误: 警告:DOMDocument :: createElement()期望参数2为字符串,给定数组
如何将数组写入xml? PHP是否有内置方法?
解决方法
基于this。
if (isset($_POST['submitProduct'])) {
// ...
$data = [
'productName' => $_POST['productName'],'productDescription' => $_POST['productDescription'],'quantity' => $_POST['quantity'],// ...
];
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($data,[$xml,'addChild']);
// ...
}