我们有一个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);
?>
发布于 2016-01-19 18:34:10
您可以使用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);
发布于 2018-06-05 04:51:16
将其转换为DOMdocument格式,并返回为XML格式;
$temp_xml = new DOMDocument();
$temp_xml->loadXML($your_xml);
$your_xml = $t_xml->saveXML($temp_xml->documentElement);
发布于 2016-01-19 23:47:13
这是我最后的代码,我唯一可能改变的是限制可以包含的Job的数量,但我们预计不会有很大的数量:
<?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);
?>
https://stackoverflow.com/questions/34874038
复制相似问题