首页 > 解决方案 > 使用php将变量写入xml文件

问题描述

嘿,我正在尝试使用 php 变量生成 XML 文件。但是 echo 或 print 似乎不起作用,请看下面的代码段。我怎样才能实现我想要做的事情?

  $xml = new DOMDocument();
 $root = $xml->createElement('package');
 $root = $xml->appendChild($root);
  $title = $xml->createElement('id' , echo $_GET['bundleid']);
   $title = $root->appendChild($title);

标签: phpxmlvariables

解决方案


正如 luenib 指出的那样,您通常不会将“echo”放在作为参数传递给函数的变量之前。下面是一个将 XML 输出到浏览器或写入文件的简单示例。

$xml = new DOMDocument();
$root = $xml->createElement('package');
$root = $xml->appendChild($root);
$title = $xml->createElement('id' , $_GET['bundleid']); // no "echo" before variable
//$title = $xml->createElement('id' , $_POST['bundleid']);
//$title = $xml->createElement('id' , $bundleid);
//$title = $xml->createElement('id' , 'bundleid');
$title = $root->appendChild($title);
$xml->formatOutput = true;
$xml_string = $xml->saveXML();

// Store XML to file.
file_put_contents('path/myXmlFile.xml',$xml_string);

// Output XML to browser.
//header("Content-type: text/xml");
//echo $xml_string;

推荐阅读