我只保存txt文件中的最后一个用户名而不是整个列表
The following code prints on screen a list of usernames. However on the fid.txt file, only the last one username is saved. What am I missing here?
foreach ($twitter_xml->channel->item as $key) {
$author = $key->guid;
preg_match("#http://twitter.com/([^\/]+)/statuses/.*#", $author, $matches);
print_r($matches[1]);
file_put_contents('fid.txt', $matches[1]);
}
以下代码在屏幕上显示用户名列表。 但是在fid.txt文件中,只保存最后一个用户名。 我在这里缺少什么? p>
foreach($ twitter_xml-> channel-> item as $ key){
$ author = $ key-> guid; \ n
epreg_match(“#http://twitter.com/([^ \ /] +)/statuses /。*#”,$ author,$ matches);
print_r($ matches [1]); \ n
file_put_contents('fid.txt',$ matches [1]);
}
code> pre>
div>
file_put_contents
overwrites the file by default. Change it to use append mode, and it'll probably do what you expect.
file_put_contents('fid.txt', "
" . $matches[1], FILE_APPEND); // also added a newline to break things up
Even better, you should append to the string, and only write to the file once:
$usernames = array();
foreach ($twitter_xml->channel->item as $key) {
// ... stuff ...
$usernames[] = $matches[1];
}
// Save everything, separated by newlines
file_put_contents('fid.txt', "
" . implode("
", $usernames), FILE_APPEND);
Unless you use the FILE_APPEND
flag, file_put_contents()
will open, write to, and close the file anew each time.
Try file_put_contents('fid.txt', $matches[1], FILE_APPEND);
You need to use file_put_contents('fid.txt', $matches[1], FILE_APPEND);
By default file_put_contents()
overwrites the file each call.
file_put_contents('fid.txt', $matches[1], FILE_APPEND);
You are overwriting the whole file each time.