以下代码在屏幕上打印用户名列表。但是,在fid.txt文件中,只保存最后一个用户名。我在这里错过了什么?
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_APPEND
标志,否则file_put_contents()
每次都会重新打开、写入和关闭文件。
尝试file_put_contents('fid.txt', $matches[1], FILE_APPEND);
您需要使用file_put_contents('fid.txt', $matches[1], FILE_APPEND);
默认情况下,file_put_contents()
会在每次调用时覆盖文件。
file_put_contents('fid.txt', $matches[1], FILE_APPEND);
您每次都会覆盖整个文件。
file_put_contents
会覆盖该文件。将其更改为使用附加模式,它可能会达到您所期望的效果。
file_put_contents('fid.txt', "'n" . $matches[1], FILE_APPEND); // also added a newline to break things up
更好的是,您应该附加到字符串中,并且只向文件写入一次:
$usernames = array();
foreach ($twitter_xml->channel->item as $key) {
// ... stuff ...
$usernames[] = $matches[1];
}
// Save everything, separated by newlines
file_put_contents('fid.txt', "'n" . implode("'n", $usernames), FILE_APPEND);