我正在尝试使用SimpleXML获取表单数据(通过_POST)并将其写入文档。这就是我所尝试的,我似乎无法让它发挥作用。
<?php
$title = $_POST['title'];
$link = $_POST['link'];
$description = $_POST['description'];
$rss = new SimpleXMLElement($xmlstr);
$rss->loadfile("feed.xml");
$item = $rss->channel->addChild('item');
$item->addChild('title', $title);
$item->addChild('link', $link);
$item->addChild('description', $description);
echo $rss->asXML();
header("Location: /success.html");
exit;
?>
非常感谢任何帮助或正确方向的观点。
答案 0 :(得分:1)
您使用asXML()函数时出错。如果要将XML写入文件,则必须将filename参数传递给它。查看SimpleXMLElement::asXML manual
所以你的代码行输出xml应该从
改变echo $rss->asXML();
到
$rss->asXML('myNewlyCreatedXML.xml');
答案 1 :(得分:0)
而不是使用SimpleXMLElement,您可以像这样直接创建XML
$xml = '<?xml version="1.0" encoding="utf-8"?>';
$xml .= '<item>';
$xml .= '<title>'.$title.'</title>';
$xml .= '<link>'.$title.'</link>';
$xml .= '<description>'.$title.'</description>';
$xml .= '</item>';
$xml_file = "feed.xml";
file_put_contents($xml_file,$xml);
这可能会对你有所帮助
答案 2 :(得分:0)
您的代码存在一些问题
<?php
$title = $_POST['title'];
$link = $_POST['link'];
$description = $_POST['description'];
//$rss = new SimpleXMLElement($xmlstr); // need to have $xmlstr defined before you construct the simpleXML
//$rss->loadfile("feed.xml");
//easier to just load the file when creating your XML object
$rss = new SimpleXML("feed.xml",null,true) // url/path, options, is_url
$item = $rss->channel->addChild('item');
$item->addChild('title', $title);
$item->addChild('link', $link);
$item->addChild('description', $description);
//header("Location: /success.html");
//if you want to redirect you should put a timer on it and echo afterwards but by
//this time if something went wrong there will be output already sent,
//so you can't send more headers, i.e. the next line will cause an error
header('refresh: 4; URL=/success.html');
echo $rss->asXML(); // you may want to output to a file, rather than the client
// $rss->asXML('outfputfile.xml');
exit;
&GT;