09/10/2018, 18:14

mình gặp vấn đề về file trong php

//rắc rối thứ nhất
khi mình sử dụng hàm fopen để lưu nội dung file
<?
$fp=$path"/info.inc";
$content=fopen($fp,"r");
echo $content;
?>
thì nó ra kết quả là: "Resource id #3"

//rắc rối thứ hai
khi mình dùng hàm đọc file:
<?
$fp=$path"/info.inc";
$content=readfile($fp);
?>
thì nó tự hiện nội dung ra mặc dù mình chưa có lệnh echo.

//yêu cầu của mình chỉ đơn giản
đọc nội dung của file vào biến $content và xử lý nó theo ý minh.
nn_future viết 20:16 ngày 09/10/2018
$fp = fopen ($fp,"r");
while (!eof($fp)) {
$content = fgets($fp);
// xu ly bien content ...
}

Ban thu xem
bpmtri viết 20:29 ngày 09/10/2018
Rắc rối thứ nhất: hàm fopen chỉ làm hàm mở file và trả về handle của file được mở thôi, chứ nó không có đọc nội dung file vào biết $content của bạn.

Rắc rối thứ hai: hàm readfile tự động dùng echo luôn.

Giải quyết hai rắc rối, xin bạn xem code của nn_future hoặc sử dụng hàm file_get_contents( chỉ dủng được với PHP version >= 4.3.0)

PHP Code:
$content file_get_contents("/user/data/file.txt"); 
nguyenthanhhuy19 viết 20:29 ngày 09/10/2018
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?
if($_REQUEST["edit"])
{
$fp = fopen("../files/aaa.txt","a");
if(!fwrite($fp, $content))
{
echo "Cannot edit file";
}
else
echo "edit file successful";
fclose($fp);
}

$fp = fopen("../files/aaa.txt","w+");
while(!feof($fp))
{
$content .= fgetss($fp,1000);
}
fclose($fp);
//echo $content;

?>
<form name="form1" method="post" action="b.php">
<table width="100%" border="0">
<tr>
<td width="17%">&nbsp;</td>
<td width="83%">&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td><textarea name="content" cols="70" rows="7"><? echo $content?></textarea></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="edit" value="edit"></td>
</tr>
</table>
</form>
</body>
</html>
tulipden viết 20:26 ngày 09/10/2018
Nguyên tắc đọc file phải theo thứ tự này nè
1. Mở file (fopen)
2. Đọc file (freads hay fgets )
3. in ra (echo )
4. Đóng file lại (fclose)
Bài liên quan
0