如何从 php://input 中删除 XML 版本

How to remove XML version from php://input

我们有一个 PHP 脚本接收 XML 以下格式的数据:

<?xml version="1.0" encoding="utf-8"?>

<job>
 <job_reference>123</job_reference>
 <job_description>Lorem ipsum.</job_description>
 <job_title>IT Manager</job_title>
 etc...
</job>

脚本当前将此写入文件,替换现有数据。然而,我们现在需要它附加到现有数据,但显然我们只能出现一次 <?xml version="1.0" encoding="utf-8"?>,否则 XML 文件将无效。我知道我需要将 fopen 模式从 'w' 更改为 'a',但我如何从 $xml 中删除 XML 版本行。当前代码为:

<?php
  $xml = file_get_contents('php://input');
  $data = $xml;
  $file = fopen( 'broadbeantesttest.xml', "w") or exit("Unable to open file!");
  // Write $somecontent to our opened file.
  if (fwrite($file, $xml) === FALSE) {
      echo "Cannot write to file ($file)";
      exit;
  }
  fclose($file);
?>

您可以使用 str_replace():

删除它
$xmlString = file_get_contents('php://input');
$xmlString = str_replace('<?xml version="1.0" encoding="utf-8"?>', '', $xmlString);
file_put_contents("broadbeantesttest.xml", $xmlString, FILE_APPEND);

这是我最终的代码,我唯一可能改变的是限制可以包含的工作数量,但我们预计不会有很大的数量:

<?php
   $new = file_get_contents('php://input');
   $new = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $new);
   $filename = "broadbean.xml";
   $handle = fopen($filename, "r");
   $old = fread($handle, filesize($filename));
   $old = str_replace('</jobs>', '', $old);
   $jobs = '</jobs>';
   $xml = $old . $new . "\r" . $jobs;
   $data = $xml;

   // Write XML File and update
   $file = fopen( 'broadbean.xml', "w") or exit("Unable to open file!");
   // Write $somecontent to our opened file.
    if (fwrite($file, $xml) === FALSE) {
        echo "Cannot write to file ($file)";
        exit;
    }
    fclose($file);
?>

如果它是 XML 你应该使用 XML API 来处理它。这将确保您正在读取和写入有效 XML。它也会处理 charsets/encodings。

一个XML只能有一个文档元素节点。追加请求数据将生成 XML 片段,而不是 XML 文档。你需要在顶层有类似 jobs 的东西。

XML 文件可能如下所示:

<?xml version="1.0" encoding="utf-8"?>
<jobs>
  <job>
   <job_reference>123</job_reference>
   <job_title>IT Manager</job_title>
  </job>
</jobs>

请求正文中的 XML 只包含一个 job 所以它可以是这样的:

<?xml version="1.0" encoding="utf-8"?>
<job>
 <job_reference>456</job_reference>
 <job_title>Programmer</job_title>
</job>

您需要加载这两个文档并将请求数据中的 job 元素导入到目标文档中。将其附加到 jobs 元素并保存。

$storage = new DOMDocument();
$storage->load($fileName);

$input = new DOMDocument();
$input->loadXml(file_get_contents('php://input'));

$storage->documentElement->appendChild(
  $storage->importNode($input->documentElement, TRUE)
);

$storage->save($fileName);

将其转换为 DOM 文档并 return 将其转换为 XML 格式;

$temp_xml = new DOMDocument();
$temp_xml->loadXML($your_xml);
$your_xml = $t_xml->saveXML($temp_xml->documentElement);