0

PHPを介してXMLデータをXMLファイルの最後に追加するスクリプトがあります。唯一の問題は、PHPスクリプトを介してXMLの新しい行を追加するたびに、余分な行(空白)が作成されることです。きちんとフォーマットされたXMLファイルを失うことなくPHPで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

すべてを 1 行にまとめないでください。より柔軟になります。

 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 に答える