此代码可以创建新的.txt文件,如果该文件尚不存在,它将创建该文件。
<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
这里的代码将每一行字符串标识为一个标记。
<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well */
$tok = strtok($string, " \n\t");
while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
?>
people.txt看起来像这样
John Smith
John Meyer
John Chase
John Smith //i want to transfer this set of string into a new file
我在这里缺少什么?
答案 0 :(得分:0)
$fp=fopen('people.txt','a+');
fputs($fp,"John Smith\r\n");
fclose($fp);
打开并附加文件,不要将其全部读入并附加到后面并将其全部写回。当文件超过一定的大小时,这将是非常低效的。我不确定你是怎么试图将它标记出来的。在我看来你可以做一个$names=file('people.txt');
并立即将它们放在一个数组中......
答案 1 :(得分:0)
$searchTerm = 'John Smith';
$file = 'people.txt';
$fileFound = 'peopleFound.txt';
$current = file_get_contents($file);
if (strpos($searchTerm, $current) !== false) {
file_put_contents($fileFound, $searchTerm."\n", FILE_APPEND);
}