0

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

?>
4

2 回答 2

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);

PS:使用DomDocument可能比字符串函数更直接,并且可以保存 XML 处理。

于 2012-10-29T16:20:59.670 回答
-1

不要将新数据追加到$result换行符上,而是执行相反的操作。

使用类似if( !empty($result) ) { result .= "\n" }的方法来避免以换行符开始 XML 数据。

于 2012-10-29T16:18:55.887 回答