Convert to array to sort - php

I have the following code which outputs the contents of text files held in a directory.
Ive been looking at the sort command in PHP but cant get it to work with the following code, I usually get an error about the input being a string and not an array.
How can I sort the directory of file before they are output?
$directory = "polls/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
list($tag, $name, $description, $text1, $text2, $text3, $date) = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
echo "<tr><td>$tag</td></tr>\n";
echo "<tr><td>$name</td></tr>\n";
echo "<tr><td>$description</td></tr>\n";
echo "<tr><td>$text1</td></tr>\n";
echo "<tr><td>$text2</td></tr>\n";
echo "<tr><td>$text3</td></tr>\n";
echo "<tr><td>$date</td></tr>\n";
echo '</table>';
}
}
closedir($dir);

First collect the entries in an array, sort it and then put it out:
$directory = "polls/";
$dir = opendir($directory);
$files = array();
while (($file = readdir($dir)) !== false) {
$files[] = $file;
}
closedir($dir);
sort($files);
foreach ($files as $file) {
// content of your original while loop
}

Another possibility is fetching the file names with glob(). Its output is sorted by default.
<?php
foreach(glob('polls/*.txt') as $file){
// ...
}
?>

Don't print it in the while loop, but store it in an array. Sort the array and then print it.
(On php.net you'll find enough different sorting functions to get the sorting method you need.)

Related

Read Files from directory and echo certain line

I want to read all files from a directory but instead of displaying the first character i want to display a certain line, f.e. line 4.
<?php
$directory = "content/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode("|", $contents);
foreach ($items as $item) {
echo "$item[0]";
}
}
}
closedir($dir);
?>
Thanks!
You can use file() function. It reads files into an array, where every line will be an array member, to skip empty lines pass the FILE_SKIP_EMPTY_LINES flag paramater.
For more info consult the docs.
// `$items` is already an array
$items = explode("|", $contents);
// if you want first element of array just:
echo $item[0];
// if you want fourth element of array just:
echo $item[3];
// without `foreach`
Could you show your file structure, please?
Basicaly you can use something like this:
$contents = file_get_contents($filename);
$items = explode("\r\n", $contents); //explode file content
foreach ($items as $item) {
echo $item[3]; //echo your line
}

PHP nested file tree

I have searched on google and on this site for something similar to what I want but nothing fits exactly and all my efforts to adapt them have failed, I want to make a script that will map out its directory and all its subfolders and the folders be at the top of the subdirectory and files after them. So far I have come up with this:
<?php
$rawParent = scandir('.');
$parentDir = array_diff($rawParent, array('.', '..','cgi-bin','error_log'));
$arrayOfDirectories = array();
$arrayOfFiles = array();
foreach ($parentDir as $child){
if(is_dir($child)){
array_push($arrayOfDirectories,$child);
}else{
array_push($arrayOfFiles,$child);
}
}
foreach ($arrayOfDirectories as $directory){
echo $directory.'<br>';
}
echo "<br>";
foreach ($arrayOfFiles as $file){
echo "<a href='".$file."'>".$file.'</a><br>';
}
?>
It's good so far but it only does the first level of the directory, can this code be adapted to go through all levels of folders and nest them? If so how? I need a few pointers, I will further use javascript to have toggles on the folders to see the contents, so I will need PHP to output something nested.
Sorry if I am not making much sense, don't really know how to explain.
Use recursive function like this :
<?php
function list_directory($directory)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
print '<ul>'.$directory.'/'.$file;
list_directory($directory.'/'.$file);
print '</ul>';
}
else
{
print "<li> $file </li>";
}
}
closedir($the_directory);
}
$path_to_search = '/var/www';
list_directory($path_to_search);
?>
Version with storage in array :
<?php
function list_directory($directory, &$storage)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
list_directory($directory.'/'.$file, $storage);
}
else
{
$storage[] = $file;
}
}
closedir($the_directory);
}
$storage = array();
$path_to_search = '/var/www';
list_directory($path_to_search, $storage);
echo '<pre>', print_r($storage,true) , '</pre>';
?>
This will do what you asked for, it only returns the sub directory names in a given path, and you can make hyperlinks and use them.
$yourStartingPath = "your string path";
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($yourStartingPath),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {
if($file->isDir()) {
$path = strtoupper($file->getRealpath()) ;
$path2 = PHP_EOL;
$path3 = $path.$path2;
$result = end(explode('/', $path3));
echo "<br />". basename($result);
}
}

how to load images from a directory in a sequence with php?

I have this php code that works great, but the only thing is that images that are loaded from the folder are random, and I need them to load numerically by order.
`
//Open images directory
$dir = opendir("../blogimg/luda_jesus");
//List files in images directoryb
while (($file = readdir($dir)) !== false)
{
if(substr( $file, -3 ) == "jpg" )
{
echo "<div class='container'><img class='lazy' id='background' src='../blogimg/loader.gif' data-original='../blogimg/luda_jesus/" . $file . "' width='884' height='587'></div>";
//echo "<br />";
}
}
closedir($dir);
?>`
Please help me
You can do this much more easily with glob:
$files = glob("../blogimg/luda_jesus/*.jpg");
natsort($files); // can also use other sort functions here, take your pick
foreach ($files as $file) {
echo '...';
}
I chose natsort as the sort function above because it will sort 2.jpg before 10.jpg, while plain sort will do the opposite. See comparison of array sorting functions for more information.
Assuming "numerically" means by filename, you can simply do you while loop and populate all files in an array, sort it, and then load the files.
Example:
//Open images directory
$dir = opendir("../blogimg/luda_jesus");
//List files in images directoryb
while (($file = readdir($dir)) !== false) {
if(substr( $file, -3 ) == "jpg" ) {
$filelist[] = $file;
}
}
closedir($dir);
sort($filelist);
for($i=0; $i<count($filelist)-1; $i++) {
echo "<div class='container'>
<img class='lazy' id='background'
src='../blogimg/loader.gif'
data-original='../blogimg/luda_jesus/" . $file . "'
width='884' height='587'>
</div>";
}
If you require different means of sorting, please mention so.

Order a directory alphabetically

I have some code that prints out the contents of a directory onto a webpage, what seems to be escaping me is how to make it print out alphabetically.
<?php
$dir="../zpress/pages"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
if(!is_dir($filename))
{
?>
<p><a href="../zpress/pages/<?php echo $filename; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
Any suggestion would be most welcome.
You can use scandir which will returns all files in the directory sorted alphabetically
$files = scandir($dir);
foreach($files as $file) {
// your code here
}
scandir
$the_files = array();
while(($filename = readdir($dir_list)) !== false) {
if(!is_dir($filename)) {
array_push($the_files,$filename);
}
}
sort($the_files);
foreach($the_files as $the_file) { ?>
<p><?php echo $the_file;?></p>
<?php } ?>
You can slurp the entire directory list into memory and then apply strnatcasecmp to sort the list:
$dir = ".";
$files = glob("$dir/*");
usort($files, 'strnatcasecmp');
// $files is now sorted
Using strnatcasecmp will give you the order in natural case sort, making for more human-readable output. See here for an explanation: http://sourcefrog.net/projects/natsort/

Getting word count for all files within a folder

I need to find word count for all of the files within a folder.
Here is the code I've come up with so far:
$f="../mts/sites/default/files/test.doc";
// count words
$numWords = str_word_count($str)/11;
echo "This file have ". $numWords . " words";
This will count the words within a single file, how would I go about counting the words for all files within a given folder?
how about
$array = array( 'file1.txt', 'file2.txt', 'file3.txt' );
$result = array();
foreach($array as $f ){
$result[$f] = str_word_count(file_get_contents($f));
}
and using the dir
if ($handle = opendir('/path/to/files')) {
$result = array();
echo "Directory handle: $handle\n";
echo "Files:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..')
continue;
$result[$file] = str_word_count(file_get_contents('/path/to/files/' . $file));
echo "This file {$file} have {$result[$file]} words";
}
closedir($handle);
}
Lavanya, you can consult the manual of readdir, file_get_contents.
Assuming the doc files are plaintext and don't contain additional markup, you can use the following script to count all of the words in all of the files:
<?php
$dirname = '/path/to/file/';
$files = glob($dirname.'*');
$total = 0;
foreach($files as $path) {
$count = str_word_count(file_get_contents($path));
print "\n$path has $count words\n";
$total += $count;
}
print "Total words: $total\n\n";
?>
If you are using *nux than you can use system('cat /tmp/* | wc -w')
You can use $words = str_word_count(file_get_contents($filepath)) to get the word count of a text file, however this won't work for word docs. You'll need to find a library or external program that can read the .doc file format.

Categories