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]);
}
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.