print out the content of a modified file
I am having a problem with outputting a modified file in php, here is my code:
<?php
$content = file_get_contents("1.txt");
$items = explode("\n",$content);
$line = "";
foreach ($items as $item){
$values = explode(",",$item);
foreach ($values as &$value){
$key = array_search($value,$values);
if ($key!=4){
$line .= $val开发者_如何学Cue.",";
}
elseif ($value=="0"){
$value="?";
$line .= $value."\n";
}
else $line .= $value."\n";
}
}
$file = fopen("1.txt","w");
fwrite($file,$line);
fclose($file);
?>
The original content in 1.txt is
1,1,1,1,1
2,2,2,2,0
The desired output is to be
1,1,1,1,1
2,2,2,2,?
However, I got this when I run the script:
1,1,1,1,1,2,2,2,2,?
,
What is the problem of my script? Thanks a lot!
You are not connecting lines with \n
correctly. Here's my bit modified function:
$content = '1,1,1,1,1
2,2,2,2,0';
$lines = explode("\n", $content);
$modLines = array();
foreach ($lines as $line)
{
$values = explode(',', $line);
foreach($values as &$value)
{
# Do here what ever you want to
if($value == '0')
$value = '?';
}
$modLines[] = implode(',', $values);
}
$content = implode("\n", $modLines);
echo $content;
Returns
1,1,1,1,1
2,2,2,2,?
精彩评论