1

我正在尝试获取表单数据(通过_POST)并使用 SimpleXML 将其写入文档。这是我尝试过的,我似乎无法让它工作。

<?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;
?>

任何帮助或正确方向的观点将不胜感激。

4

3 回答 3

1

您错误地使用了 asXML() 函数。如果要将 XML 写入文件,则必须将文件名参数传递给它。检查SimpleXMLElement::asXML 手册

所以你的代码行输出 xml 应该从

echo $rss->asXML();

$rss->asXML('myNewlyCreatedXML.xml');
于 2013-10-09T12:54:21.537 回答
0

您可以像这样直接创建 XML 而不是使用 SimpleXMLElement

$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);

这可能会帮助你

于 2013-10-09T12:32:44.543 回答
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;

?>

于 2013-10-09T12:58:39.473 回答