从文本文件加载一个数字并将其用作对象

时间:2012-05-29 16:29:28

标签: php string object

我想加载一个带有数字的文件并将其用作数字(而不是字符串)。这有什么解决方案吗?我得到的错误

Call to a member function seek() on a non-object 

我的PHP代码

$in = fopen('emails.txt','r');
$out = fopen('currentposition.txt', 'r+');
$pos = file_get_contents('currentposition.txt');
$in->seek($number1); 
while($kw = trim(fgets($in))) {
    //my code
    $position = $in->current();
    fwrite($out, $position);
}

fclose($in);
fclose($out);

3 个答案:

答案 0 :(得分:1)

文件

$ cat /tmp/ll
9

剧本:

<?php

$x = file_get_contents("/tmp/ll");
echo $x + 10;
?>

输出:     19

答案 1 :(得分:0)

使用$pos代替$number1 ...?

答案 2 :(得分:0)

答案在您收到的错误消息中:它表示您正在调用方法,即对象的成员函数,用于不是对象的内容< / strong>(在面向对象编程意义上)。 $in不是类的对象,只是resource

修改

现在我理解你要完成的任务试试这个:

// use w - to truncate when writing (overwrite), b - in case you ever run this on Windows
$recordFile = fopen('currentposition.txt', 'wbr');
$emailsFile = fopen('emails.txt', 'r');
$pos = trim(fgets($recordFile));
// if first time and there was no 0 in the currentposition.txt
if(!isset($pos))
    $pos = 0;

//set the pointer
fseek($emailsFile, $pos);

// read the contents;
$content = fread($emailsFile, filesize($emailsFile));

// get the current position of the file pointer
$pos = ftell($emailsFile);

// write the last position in the file
fwrite($recordFile, $pos);

fclose($recordFile);
fclose($emailsFile);

说实话,这应该有效但尚未经过测试。我希望你能得到一般的想法。

添加

上面的代码一次性将电子邮件文件的所有内容读入一个(字符串)变量。然后,您可以使用\n作为分隔符(例如$allEmails = split('\n', $content); )将其拆分,并将电子邮件放在数组中,您可以通过该数组循环。 无论如何,这里是相同的代码但是使用while循环,即逐行读取文件 - 对于非常大的文件(MBytes)会有好处

// use w - to truncate when writing (overwrite), b - in case you ever run this on Windows
$recordFile = fopen('currentposition.txt', 'wbr');
$emailsFile = fopen('emails.txt', 'r');
$pos = trim(fgets($recordFile));
// if first time and there was no 0 in the currentposition.txt
if(!isset($pos))
    $pos = 0;

//set the pointer
fseek($emailsFile, $pos);


// while end of file is not reached
while(!feof($emailsFile)){
    // read one line of the file and remove leading and trailing blanks
    $kw = trim(fgets($emailsFile));
    // .... do something with the line you've read
    // get the current position of the file pointer
    $pos = ftell($emailsFile);    
    // you don't need to write the position in the $recordFile every loop!
    // saving it in $pos is just enough
}

// write the last position in the file
fwrite($recordFile, $pos);

fclose($recordFile);
fclose($emailsFile);