2016-06-21 38 views
0

因此,我試圖實現的是將PHP中的變量加載到XML文件中。將PHP變量加載到XML文件中

這是我的XML如何看待當下:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<firstname></firstname> 
<lastname></lastname> 

這是我的PHP在那裏我試圖將變量保存到XML

 $file = simplexml_load_file("filename.xml"); 

     $xml->firstname = "Mark"; 

     $xml->lastname = "Zuckerberg"; 

     file_put_contents($file, $xml->asXML()); 

如果我嘗試打印此我得到以下錯誤信息:

Call to undefined method stdClass::asXML() in ... on line 1374 

有什麼建議嗎?

+0

'$文件= ...'+'$ XML-> asXML()' –

回答

1

您不會創建初始XML文件,您正在使用的庫會爲您創建它。

XML DOM是這份工作的最佳選擇。

$xml = new DOMDocument();         # Create a document 
$xml_firstname = $xml->createElement("firstname", "Over"); # Create an element 
$xml_lastname = $xml->createElement("lastname", "Coder"); # Create an element 
$xml->appendChild($xml_firstname);       # Add the element to the document 
$xml->appendChild($xml_lastname);       # Add the element to the document 
$xml->save("myfancy.xml");         # Save the document to a file 

輸出將

<?xml version="1.0" encoding="utf-8"?> 
<firstname>Over</firstname> 
<lastname>Coder</lastname> 
+0

這給我一個「Class'DOMDocument'在TestController.php中找不到1360行」 –

+0

@MarcelWasilewski你使用什麼系統?如果Linux有什麼發行版? – OverCoder

+0

你需要安裝它,如果你有Ubuntu或者Debian,在你的系統終端中執行'sudo apt-get install php5-dom',如果你有Red Hat/Fedora/Cent OS你需要'yum install php-xml' – OverCoder

0

首先:您在哪建立$xml

您可以從$file = ...開始,但是請將該對象稱爲$xml

要麼改變對象名稱來$xml或更改引用$file

$xml = simplexml_load_file("filename.xml"); /* note the object name change */ 
$xml->firstname = "Mark"; 
$xml->lastname = "Zuckerberg"; 

接下來,你file_put_contents()命令不正確。第一個參數是accept是文件名,但在您的示例中,$file不是名稱,而是simplexml對象。

$xml->asXML("path/to/file.xml"); 

最後,你的腳本輸出錯誤:

Call to undefined method stdClass::asXML()

file_put_contents("path/to/file.xml", $xml->asXML()); 

另外,這樣做(感謝bassxzero)使用asXML()方法與路徑

這意味着你不能撥打$xml->axXML() as(我假設)該方法不存在,或者該對象沒有正確的方法。

最初更改對象的名稱(第一個問題)應該修復此問題!

+0

代替file_put_contents叫他可以用'$ XML-> asXML ('path/to/file.xml');' – bassxzero

+0

@bassxzero更新了我的答案,謝謝 – Ben

+0

我已經像上面提到的那樣完成了它,仍然得到相同的錯誤消息。 –

0

從代碼中,將XML加載到$ file中。 但你編輯$ xml。下面的代碼應該工作

$xml = simplexml_load_file("filename.xml"); 
$xml->firstname = "Mark"; 
$xml->lastname = "Zuckerberg"; 
file_put_contents("output.xml", $xml->asXML()); 
1

啓用錯誤報告(如error_reporting(E_ALL);),你很快就會明白爲什麼它不工作:

Warning: simplexml_load_file(): xml.xml:3: parser error : Extra content at the end of the document 
// your XML is not correctly formatted (XML requires a root node) 

Warning: Creating default object from empty value 
// $xml->firstname when $xml does not exists 

要解決的是,你的XML應該是這樣的:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<data><!-- here comes the root node --> 
<firstname></firstname> 
<lastname></lastname> 
</data> 

而且PHP應該看起來像以前的答案:

$xml = simplexml_load_file("filename.xml"); 
$xml->firstname = "Mark"; 
$xml->lastname = "Zuckerberg"; 
file_put_contents("filename_copy.xml", $xml->asXML());