我有一个脚本,可以通过PHP将XML数据附加到XML文件的末尾。唯一的问题是,在我通过PHP脚本添加的每一行新XML之后,会创建一个额外的行(空白)。有没有办法用PHP从XML文件中删除空格而不会丢失整齐的XML文件?这是我写入XML文件的PHP代码:
<?php
function formatXmlString($xml) {
// add marker linefeeds to aid the pretty-tokeniser (adds a linefeed between all tag-end boundaries)
$xml = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $xml);
// now indent the tags
$token = strtok($xml, "\n");
$result = ''; // holds formatted version as it is built
$pad = 0; // initial indent
$matches = array(); // returns from preg_matches()
// scan each line and adjust indent based on opening/closing tags
while ($token !== false) :
// test for the various tag states
// 1. open and closing tags on same line - no change
if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)) :
$indent=0;
// 2. closing tag - outdent now
elseif (preg_match('/^<\/\w/', $token, $matches)) :
$pad=0;
// 3. opening tag - don't pad this one, only subsequent tags
elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) :
$indent=4;
// 4. no indentation needed
else :
$indent = 0;
endif;
// pad the line with the required number of leading spaces
$line = str_pad($token, strlen($token)+$pad, ' ', STR_PAD_LEFT);
$result .= $line . "\n"; // add to the cumulative result, with linefeed
$token = strtok("\n"); // get the next token
$pad += $indent; // update the pad size for subsequent lines
endwhile;
return $result;
}
function append_xml($file, $content, $sibling, $single = false) {
$doc = file_get_contents($file);
if ($single) {
$pos = strrpos($doc, "<$sibling");
$pos = strpos($doc, ">", $pos) + 1;
}
else {
$pos = strrpos($doc, "</$sibling>") + strlen("</$sibling>");
}
return file_put_contents($file, substr($doc, 0, $pos) . "\n$content" . substr($doc, $pos));
}
$content = "<product><id>3</id><name>Product 3</name><price>63.00</price></product>";
append_xml('prudcts.xml', formatXmlString($content), 'url');
?>
答案 0 :(得分:0)
不要只把所有内容放在一行中,而且你更灵活:
return file_put_contents($file, substr($doc, 0, $pos) . "\n$content" . substr($doc, $pos));
相反(建议):
$buffer = substr($doc, 0, $pos) . "\n$content" . substr($doc, $pos);
$buffer = rtrim($buffer);
return file_put_contents($file, $buffer);
P.S:使用DomDocument
可能更直接,为XML处理保存字符串函数。
答案 1 :(得分:-1)
不要将新数据附加到$result
然后添加换行符,而是反过来。
使用if( !empty($result) ) { result .= "\n" }
之类的内容来避免使用换行符开始使用XML数据。