2013-10-09 74 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

相關問題