我有一个脚本,通过 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');
?>