Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //Answer to: http://stackoverflow.com/questions/7180128/php-read-data-from-several-text-files-outputting-a-certain-line-from-all-files/
- 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;
- }
- //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>";
- ?>
Advertisement
Add Comment
Please, Sign In to add comment