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
}
Related
i want to read test.txt file line by line that i converted it to object but my problem is it just read line 1 and something is wrong because loading is little long
$file = fopen(__DIR__.'/test.txt','r');
while (!feof($file)){
$file = fgets($file);
$obj = json_decode($file);
echo $obj->sid;
echo "<hr>";
}
this my test.txt:
{"sid":5555,"trans-id":"PROV_149663920543900000801","status":"0","base-price-point":"0","msisdn":"989905978846","keyword":"sub1","validity":1}
{"sid":2244,"trans-id":"PROV_149663920543900000801","status":"0","base-price-point":"0","msisdn":"989905978846","keyword":"sub1","validity":1}
You are overwriting $file on line 3 of your code. Change it to $line and you are good to go.
$file = fopen(__DIR__.'/test.txt','r');
while (!feof($file)){
$line = fgets($file);
$obj = json_decode($line);
echo $obj->sid;
echo "<hr>";
}
Try this:
<?php
$filename= __DIR__.'/test.txt';
$array = explode("\n", file_get_contents($filename));
foreach ( $array as $line)
{
$obj = json_decode($line);
echo $obj->sid;
echo "<hr>";
}
?>
Use the file() function:
$contents = file(__DIR__.'/test.txt');
foreach ($contents as $line)
{
$obj = json_decode($line);
echo $obj->sid;
echo "<hr>";
}
The file() function read a file and create an array with each line of the file's contents.
I'd suggest using file to read the file as this generates the individual lines as array entries so you can iterate though each line using a foreach
$file=__DIR__ . '/json_src.txt';
$lines=file($file);
foreach( $lines as $line ){
$json=json_decode( $line );
printf('%s<hr />', $json->sid );
}
I have a piece of PHP code as follows:
$write_URLs = fopen("links/WriteURLs.txt", "w");
foreach ($list_URLs as $htmlLink) {
GetURLs ($htmlLink);
foreach ($URLs as $URL) {
fwrite($write_URLs, $URL ."\n");
}
}
fclose($write_URLs);
Above code writes the URLs on links/WriteURLs.txt on every execution and so the WriteURLs.txt file can not save the results of the previous execution.
The problem is that I want to check if links/WriteURLs.txt exists, then start to write the URLs on a new file, such as links/01-WriteURLs.txt, links/02-WriteURLs.txt, ... . After that I want to start reading the URLs from the generated file (i.e. not all files, only the one which is generated in the last step) links/WriteURLs.txt, links/01-WriteURLs.txt, links/02-WriteURLs.txt or ..., and echo the HELLO WORLD foreach URL. Below you can see the incomplete version of the code that I tried to develop. Could you please help me how to solve this problem? thanks
$i = 1;
$write_URLs = fopen("links".DIRECTORY_SEPARATOR. $i. "-WriteURLs.txt", "w");
if(file_exists($write_URLs)) {
fclose($write_URLs);
$new_write_URLs = fopen("links".DIRECTORY_SEPARATOR. $i++. "-WriteURLs.txt", "w");
} else {
foreach ($list_URLs as $htmlLink) {
GetURLs ($htmlLink);
foreach ($URLs as $URL) {
fwrite($new_write_URLs, $URL ."\n");
}
}
}
fclose($new_write_URLs);
$trimmed = file(???????????, FILE_IGNORE_NEW_LINES);
foreach ($trimmed as $URL) {
echo "Hello World";
}
If you'd like to read the data from the text file you just finished writing, you could simply keep track of the name of the file you are working with and then use it later during the read, like this:
$i = 0;
do {
$filename = "links".DIRECTORY_SEPARATOR . $i++ . "-WriteURLs.txt";
} while (file_exists($filename));
$write_URLs = fopen($filename, "w");
foreach ($list_URLs as $htmlLink) {
$URLs = GetURLs ($htmlLink);
foreach ($URLs as $URL) {
fwrite($write_URLs, $URL ."\n");
}
}
fclose($write_URLs);
$trimmed = explode("\n",file_get_contents( $filename ) );
foreach ($trimmed as $URL) {
echo "Hello World";
}
how to get only the specific content from a file using PHP.
I have a file with content:
reference 1.pdb
mobile 4r_1.pdb
ignore
fit
mobile 4r_10.pdb
ignore
fit
mobile 4r_22220.pdb
ignore
fit
Now, I want to take all the names i.e. (output)
4r_1
4r_10
4r_22220
in an array and print it.
The program i have written in php doesn't work properly, can have a look
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
$output4 = preg_grep("/mobile/i",$convert); //take only the line starts with mobile and put it in an array
if ($output4 !="/mobile/i")
{
print $output4;
print "\n";
}
Please help! to extract only the names
Try this:
$convert = explode("\n", $data); // take it in an array
$filenames = array();
foreach ($convert as $item) {
if(strstr($item,'mobile')) {
array_push($filenames,preg_replace('/mobile[\s]?([A-Za-z0-9_]*).pdb/','${1}',$item));
}
}
Now all the file names (assuming they are file names) are in the array $filenames
preg_grep returns an array of matching lines, your condition is treating $output4 as a string.
Loop over the array to print out each line and use either substr or str_replace to remove the unwanted characters from the string
$data = file_get_contents('test.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
$output4 = preg_grep("/mobile/i",$convert); //take only the line starts with mobile and put it in an array
foreach($output4 as $entry) {
print str_replace("mobile ", "", $entry) . "\n";
}
Below code should work:
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
$output4 = preg_grep("/mobile/i",$convert);
if (count($output4))
{
foreach ($output as $line) {
print $line; // or substr($line, 6) to remove mobile from output
print "\n";
}
}
Note:
Instead of doing
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
You may read a file into array with file() function:
$convert = file('file.txt'); // to read the file
Try this:
$content = file_get_contents('file.txt');
$lines = explode("\n", $content);
foreach ($lines as $line) {
if (preg_match('/^mobile\s+(.+)$/', $line, $match)) {
echo $match[1], "\n";
}
}
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.
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.)