0

将表单数据保存到 xml 时遇到一点问题。我尝试将新元素 ($ukey) 添加到 xml 对象,但它给了我一个与 $ukey 变量一致的错误。$newItem->appendChild($xml->createElement('ukey', $ukey));

// Script by Fred Fletcher, Canada.
$fname = $_POST['name'];
$lname = $_POST['email'];
$location = $_POST['cat'];
$report = $phone;
$description = $_POST['content'];
$ukey = date("dmYHis");


$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->load('/home/mysite/public_html/file.xml');

$element = $xml->getElementsByTagName('reports')->item(0);

$timestamp = $element->getElementsByTagName('timestamp')->item(0);
$fname = $element->getElementsByTagName('fname')->item(0);
$lname = $element->getElementsByTagName('lname')->item(0);
$location = $element->getElementsByTagName('location')->item(0);
$report = $element->getElementsByTagName('report')->item(0);
$description = $element->getElementsByTagName('description')->item(0);
$ukey = $element->getElementsByTagName('ukey')->item(0);

$newItem = $xml->createElement('reports');

$newItem->appendChild($xml->createElement('timestamp', date("F j, Y, g:i a",time())));;

$newItem->appendChild($xml->createElement('fname', $_POST['name']));
$newItem->appendChild($xml->createElement('lname', $_POST['email']));
$newItem->appendChild($xml->createElement('location', $_POST['cat']));
$newItem->appendChild($xml->createElement('report', $phone));
$newItem->appendChild($xml->createElement('description', $_POST['content']));
$newItem->appendChild($xml->createElement('ukey', $ukey));

$xml->getElementsByTagName('entries')->item(0)->appendChild($newItem);

$xml->save('/home/mysite/public_html/file.xml');

这是错误

Warning: DOMDocument::createElement() expects parameter 2 to be string, object given in /home/mysite/public_html/wp-content/themes/twentytwelve/myform.php on line 214

Catchable fatal error: Argument 1 passed to DOMNode::appendChild() must be an instance of DOMNode, null given, called in /home/mysite/public_html/wp-includes/template-loader.php on line 47 and defined in /home/mysite/public_html/wp-content/themes/twentytwelve/myform.php on line 214

和 xml 示例

<?xml version="1.0" encoding="UTF-8"?>
<entries>
  <reports>
   <timestamp>September 19, 2013, 11:45 am</timestamp>
   <fname>John Snider</fname>
   <lname>mailATemail.com</lname>
   <location>156</location>
   <report>08974545153</report>
   <description>jhsdhfsdfgsdtasrgsfgasf</description>
   <ukey>156152</ukey>
  </reports>
</entries>

我需要将其更改为字符串还是有什么问题?

澄清一下,在我添加 $ukey 之前,脚本运行良好

谢谢

4

1 回答 1

2
$ukey = date("dmYHis");

是的,这应该是一个不错的包含格式化日期的字符串值,很好。

$ukey = $element->getElementsByTagName('ukey')->item(0);

哎呀,你在这里做什么……?

$newItem->appendChild($xml->createElement('ukey', $ukey));

现在,$ukey 不再是一个字符串值了,因为前面引用的那一行——你把变量名弄乱了,伙计。

于 2013-09-19T11:23:38.020 回答