2013-10-09 75 views
1

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

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

Yo你不能'回声'的东西,然后使用'header()'。 – Shikiryu

+0

总是发布运行代码时发生的错误。 –

回答

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

可能,这将帮助你

+0

这个。是。丑陋。 – Shikiryu

1

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

所以你的代码行oututing XML应该从

echo $rss->asXML(); 

改为

$rss->asXML('myNewlyCreatedXML.xml'); 
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; 

?>

+0

我得到一个'解析错误:语法错误,意想不到的T_VARIABLE在/documentname.php行10错误与此。是否因为第9行没有分号?因为当我放入一个时,我得到了'致命错误:class'SimpleXML'没有在第9行的/documentname.php中找到 – user2012648

相关问题