PHP在IE Vista上保存文件,添加换行符

时间:2011-10-25 23:19:41

标签: php

我尝试使用formatoutput = true来格式化PHP函数中的XML输出,但是没有这样做。所以我想用一个函数做这个。我找到了两个不同的脚本,但它们都有相同的问题:它们做缩进但新行“\ n”不会打印在文件中。是否有不同的方式来获取换行符?

PHP脚本

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

function make_update( $nodeid, $name, $top, $left, $width, $height ) {

$nodes = new SimpleXMLElement('linkcards.xml', null, true);

$returnArray = $nodes->xpath("//LINKCARD[@ID='$nodeid']");  
$node = $returnArray[0]; 
$node->NAME = $name;
$node->TOP = $top;
$node->LEFT = $left;
$node->WIDTH = $width;
$node->HEIGHT = $height;

$nodes->asXML('linkcards.xml');

$formatted = formatXmlString($nodes->asXML());

$file = fopen ('linkcards.xml', "w"); 
fwrite($file, $formatted); 
fclose ($file);  

}

echo make_update(trim($_REQUEST['nodeid']),trim($_REQUEST['name']),trim($_REQUEST['top']),trim($_REQUEST['left']),trim($_REQUEST['width']),trim($_REQUEST['height']));

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--;
    // 3. opening tag - don't pad this one, only subsequent tags
    elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) :
      $indent=1;
    // 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;
}

?>

1 个答案:

答案 0 :(得分:0)

找到答案。如果我为换行符写“\ r \ n”,它可以工作!!!!!!

$result .= $line . "\r\n"; 

对于格式化XML输出格式有困难的其他人来说,使用该函数而不是formatoutput = true可能是一个有用的解决方法。