我想写一个脚本,读取25个重文本文件的内容(每个约100行)。我希望我的脚本输出每个文本文件的第5行。我还在windows工作站工作(在本地环境中使用Apache进行测试)。
每个文本文件位于同一目录(即products/product1.txt),我想这使它更容易。
在第5行,每个文本文件看起来像这样(有不同的描述):
Product Desc: iphone
我还想知道是否有可能,在实现上述目标后,让脚本删除文本"Product Desc:",以便仅显示实际的产品描述。
请提供任何代码示例,因为我是一个新手:)
$dir = opendir('directory');
while($file = readdir($dir)){
if ($file != "." or $file != ".."){
$opened = file($file);
echo $opened[4]."<br />";
}
}
所以这基本上是三部分:(1)您需要遍历目录,(2)读取每个文件的第五行,(3)您需要读取该行冒号之后的部分。
// open the products directory
$fileHandle = opendir('products');
// create an array to store the file data
$files = array();
// create an array to store products
$products = array();
if ($fileHandle) {
// loop through each file
while ( false !== ($singleFile = readdir($fileHandle)) ) {
// use file() to read the lines of the file
$lines = file($singleFile);
// store the fifth line in each file (the array starts at 0)
$productDescription = explode(":",$lines[4]);
$products[] = productDescription[1]; // the bit after the colon
}
}
// this should show you an array of the products
print_r($products);
PHP加载多个文件:
<?php
date_default_timezone_set("America/Edmonton");
$products=array();
$dir="../products/"; //Set this for whatever your folder
function getProduct($file) {
$fp=fopen($file,"r");
//Read five lines
for ($j=0;$j<5;$j++) $line=fgets($fp);
$GLOBALS["products"][]=substr($line,14);//Since products is a global var
fclose($fp);
}
$dp=opendir($dir);
while (($file = readdir($dp)) !== false) {
if ($file!="." && $file!="..")
getProduct($dir.$file);
}
closedir($dp);
//Review the product list
print_r($products);
?>
示例文件one.txt:
line 1
line 2
line 3
line 4
Product Desc: iPhone
line 6
快捷方式:
因为我们只需要第五行,所以我们使用$j
循环读取前五行,每一行都覆盖最后一行。如果文件少于5行,你将从$line
中得到null
…您应该对此进行测试(而不是将其添加到产品列表中)。最后,因为我们现在知道字符串"Product Desc:
"的长度(您写它的方式),我们可以把该行的第一部分丢掉。这不是很健壮,最好使用RegEx或字符串解析来确保正确的单词在那里,然后使用冒号后面的数据。仍然……它回答了你最初的问题;)
你说可以有更多行,这种方法只将前5行加载到内存中(每一行重写最后一行),并在到达第五行时停止…这意味着比将整个文件读入数组(file
)然后只使用第5行有更大的性能和内存优势。
设计决策:
看起来你正在构建一个产品目录,使用数据库来存储这些数据会更好。不必是什么大问题(MySQL, PostgreSQL),它可以像SQLite一样简单。
答案:http://pastebin.com/WBBQW9wA (底部原始代码)
这个过程分为三个部分。
- 获取目录中所有的文件名
- 读取每个文件的第五行。
- 冒号后分割。
我的方法有很好的文档和理解。它使用函数来完成进程的特定部分。它很容易理解发生了什么,同时也相当健壮。
完成工作的函数:
<?php
function readAfterColon($string) {
/**
* @param string $string The string you'd like to split on.
*
* @return string The data after the colon. Multiple colons work just fine.
*/
$array = explode(":",$string, 2);
return isset($array[1]) ? $array[1] : '';
}
function readLine($lineNumber, $fileName) {
/**
* @param int $lineNumber The line number you want to read from the file.
* @param string $fileName The string representing the file you wish to open.
*
* @return string The contents of the line in the file.
*/
$file = file($fileName);
return $file[$lineNumber-1];
}
function readLineFrom($lineNumber, $fileNames) {
/**
* @param int $lineNumber The line number you want to read from the file.
* @param string|array $files Either a string for the file you want to open, or an array of filenames.
*
* @return array An associative array of the filename to the contents of the line.
*/
$lines = array();
if(is_array($fileNames)) {
foreach($fileNames as $fileName) {
$lines[$fileName] = readLine($lineNumber, $fileName);
}
} else {
$lines[$fileNames] = readLine($lineNumber, $fileNames);
}
return $lines;
}
function getFileNamesFromDirectory($directory = '.') {
/**
* @param string $directory The path to directory you'd like to get filenames from. Defaults to current directory.
*
* @return array An array of filenames. Empty if there are no files.
*/
$fileNames = array();
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileNames[] = $directory . $file;
}
}
closedir($handle);
}
return $fileNames;
}
?>
的例子:
<?php
//include the functions, then:
//get the line from every file
$descriptions = readLineFrom(5, getFileNamesFromDirectory('/var/www/test/'));
//get the contents after the colon
foreach($descriptions as $fileName=>$description) {
$descriptions[$fileName] = readAfterColon($description);
}
//display it
echo "<pre>'n";
print_r($descriptions);
echo "</pre>";
?>