将PHP变量加载到XML文件中

时间:2016-06-21 14:03:14

标签: 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

有什么建议吗?

4 个答案:

答案 0 :(得分: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());

答案 1 :(得分: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>

答案 2 :(得分:0)

首先关闭:你在哪里建立XmlElement headerElement = document.DocumentElement["ReplayHeader"]; string errorMessage = headerElement.Attributes["errorMessage"].Value; errorCode = headerElement.Attributes["returnCode"].Value;

您从$xml开始,然后将对象称为$file = ...

将对象名称更改为$xml或将引用更改为$xml

$file

接下来,您的$xml = simplexml_load_file("filename.xml"); /* note the object name change */ $xml->firstname = "Mark"; $xml->lastname = "Zuckerberg"; 命令不正确。第一个参数是accepted是文件名,但在您的示例中,file_put_contents()不是名称而是$file对象。

simplexml

或者,通过执行此操作将file_put_contents("path/to/file.xml", $xml->asXML()); 方法与路径一起使用(感谢 bassxzero ):

asXML()

最后,您的脚本输出错误:

  

调用未定义的方法stdClass :: asXML()

这意味着您无法调用$xml->asXML("path/to/file.xml"); (我假设)该方法不存在,或者该对象没有正确的方法。

最初更改对象的名称(第一期)应该解决这个问题!

答案 3 :(得分:0)

从代码中,将XML加载到$ file中。 但是你编辑$ xml。以下代码应该可以使用

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