使用php

时间:2016-04-15 08:05:35

标签: php

我的文字文件包含以下行:

text1
text2
text3

我需要在文字

之前和之后添加标签

输出

<h1>text1</h1>
<h1>text2</h1>
<h1>text3</h1>

我正在使用此脚本

$file = file_get_contents("test.txt");
$handle = fopen($file);
$output = '';
while (($line = fgets($handle)) !== false)     {
$output .= '<h1>' . $line .'</h1>' . "\n";
}
fclose($handle);
file_put_contents($output, $file);

我收到了这个错误:

  

警告:fopen()需要至少2个参数,1在第4行中给出       警告:fgets()期望参数1是资源,第7行给出布尔值       警告:fclose()期望参数1为资源,第10行中给出布尔值       警告:file_put_contents():第11行中的文件名不能为空

1 个答案:

答案 0 :(得分:0)

fopen();函数中有一个参数模式,它指定了您对流所需的访问类型,因此您会收到警告..了解有关f_open()的更多信息。

这里我有两种方法可以在文件中写入

方法1:使用file_get_contents()file_put_contents()

$file = 'test.txt';
// Open the file to get existing content
$current = file_get_contents($file);
$rows = explode("\n", $current);
$output= '';
foreach($rows  as $row)
{
    $output .= '<h1>'.$row.'</h1>'. "\n";
}
file_put_contents($file, $output);

方法:2 您正在尝试使用

$file = 'test.txt';
$current = file_get_contents($file);
$handle = fopen($file,'r');
$output = '';
while (($line = fgets($handle)) !== false)    
{
    $output .= '<h1>'. $line .'</h1>'."\n";
}
fclose($handle);
file_put_contents($file, $output);
相关问题