簡體   English   中英

將PHP變量加載到XML文件中

[英]Load PHP variables into XML file

因此,我試圖實現的是將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

有什么建議么?

啟用錯誤報告(例如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());

您沒有創建初始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>

首先,您在哪里建立$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()命令不正確。 第一個參數accepts是文件名,但是在您的示例中$file不是名稱,而是simplexml對象。

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

或者,通過執行以下操作,將asXML()方法與路徑結合使用(感謝bassxzero ):

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

最后,您的腳本輸出錯誤:

調用未定義的方法stdClass :: asXML()

這意味着您不能調用$xml->axXML()因為(我假設)該方法不存在,或者該對象沒有正確的方法。

最初更改對象名稱(第一個問題)應該可以解決此問題!

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM