Loop each array element in PHP - php

I am looking for a way to read each line of a text document as an array element.
<?php
$file = fopen("nums.txt", "r");
$i = 0;
$line = "";
$access_key = '1234567890';
while (!feof($file)) {
$line .= fgets($file);
}
$numbers = explode("\n", $line);
for ($i=0; $i < count($numbers); $i++) {
$ch = curl_init('http://apilayer.net/api/validate?access_key='.$access_key.'&number='.$numbers[$i].'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
$validationResult = json_decode($json, true);
echo $numbers[$i] . '</span>' . $validationResult['valid'] . ' ' . $validationResult['country_code'] . ' ' . $validationResult['carrier'];
}
fclose($file);
?>
Any tips are appreciated.
Cheers!

$numbers = explode(PHP_EOL, $line);
Is this what you wanted?
Updated with PHP_EOL

You could save a lot of work. Read into an array and trim the \n and/or \r and foreach():
$numbers = array_map('trim', file('nums.txt'));
foreach($numbers as $number) {
// echo $number
}

// Get the file content by path.
$file = file_get_contents($file);
// Break the file into array of lines.
$lines = preg_split('/\r*\n+|\r+/', $file);
// Remove last element as the last \r\n adds an extra element into the array.
array_pop($lines);
// Iterate over each line.
foreach($lines as $line_number => $line_content){
// do something...
}

Related

Remove blank from text file

I want to remove blank line from this text file :
test1
test2
test3
test4
So I try this code in PHP :
$file = __DIR__.$namefile;
foreach ($file as $k => $v) {
if (!trim($v))
unset($lines[$k]);
}
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
$array1[] = $nl;
}
But it does not work. Thanks for your help !
How about exploding each new line and checking if it's empty?
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array();
foreach ($lines AS $line) {
if (!empty($line)) {
$result[] = $line;
}
}
$result = implode("\n", $result);
Or, as Henders suggests, look at https://stackoverflow.com/a/7972266/1441858:
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array_filter($lines, 'trim');
$result = implode("\n", $result);
$file = __DIR__.$namefile;
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
if (trim($line) != "") {
$array1[] = $nl;
}
}
fclose($f);
$file = __DIR__.$namefile;
$lines = explode("\n", file_get_contents($file));
$result = array_filter($lines);
echo implode("\n", $result);
file_put_contents($file, implode("\n", $result)); //save
Or use:
$result = array_filter($lines, 'trim');
If there can be whitespaces in blank lines.

Adding a string to the end of each line but not the first line

I am trying to add a string to the end of eachline. So far this works. However I dont want the string to be added to the end of the first line. How can I do this?
So far i have got:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
while(!feof($baseFile)) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
I have also tried to loop it by doing this:
<?php
$EOLString="string \n";
$fileName = "file.txt";
$baseFile = fopen($fileName, "r");
$newFile="";
$x = 0;
while(!feof($baseFile)) {
if ($x > 0) {
$newFile.= str_replace(PHP_EOL, $EOLString, fgets($baseFile));
}
$x++;
}
fclose($baseFile);
file_put_contents("newfile.txt", $newFile);
$bingName = "newfile.txt";
$bingFile = fopen($bingName, "a+");
fwrite($bingFile,$EOLString);
fclose($bingFile);
?>
So the end result would look like:
firstonestring
secondonestring
thirdonestring
and so on.
I hope you can help me!
Ben :)
Just add a counter to your loop:
$counter = 0;
while(!feof($baseFile)) {
$line = fgets($baseFile)
if($counter++ > 0){
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}else{
$newFile.= $line . "\n";
}
}
Also, you seem to be writting the new file, only to reopen it and append more data. There is no need to do that, just append to the contents before you write it the 1st time:
fclose($baseFile);
file_put_contents("newfile.txt", $newFile . $EOLString);
//$bingName = "newfile.txt";
//$bingFile = fopen($bingName, "a+");
//fwrite($bingFile,$EOLString);
//fclose($bingFile);
Alternativly, you can just read in the whole file, split into lines, and rejoin:
$EOLString="string \n";
$lines = explode("\n", file_get_contents("file.txt"));
$first = array_shift($lines);
file_put_contents("newfile.txt", $first . "\n" . implode($EOLString, $lines) . $EOLString);
//done!
By using a flag
$first = TRUE;//set true first time
while (!feof($baseFile)) {
$line = fgets($baseFile);
if (!$first) {// only enter for false
$newFile.= str_replace(PHP_EOL, $EOLString, $line);
}
$first = FALSE;// set false except first
}

PHP: Insert line break after every $num word in a text file

I want to clean up a .txt file to make it more readable by inserting a line break after every 4th word. The file has been filled with data from an array.
This is what I've come up with so far by looking at this and this:
<?php
require "simple_html_dom.php";
$html = file_get_html("http://www.lipsum.com/");
$data = array();
$counter = 0;
foreach($html->find("div") as $tr){
$row = array();
foreach($tr->find("div") as $td){
$row[] = $td->plaintext;
}
$data[] = $row;
}
ob_start();
var_dump($data);
$data = preg_replace('~((\w+\s){4})~', '$1' . "\n", $data);
file_put_contents('new_text_file.txt', $data);
//$handlefile = fopen("newfile.txt", "w") or die("Unable to open file!");
//file_put_contents('newfile.txt', $data);
//$output = ob_get_clean();
//$outputFile = "newfile.txt";
//fwrite($handlefile, $output);
//fclose($handlefile);
?>
As you can see I've created a for loop and two if statements to "count" the spacing between the words, and when the counter variable has reached 3, a line break is inserted. But it doesn't work since no data from the website is printed to the text file in the first place. It works however, if I remove the for loop and the if statements, without the sorting of course.
Any type of help is appriciated!
Edit: updated code.
Edit 2: final working version. Original question left for further reference.
This is the final working version:
<?php
require "simple_html_dom.php";
$html = file_get_html("http://www.lipsum.com/");
$data = array();
$counter = 0;
foreach($html->find("div") as $tr){
$row = array();
foreach($tr->find("div") as $td){
$row[] = $td->plaintext;
}
$data[] = $row;
}
ob_start();
var_dump($data);
$handlefile = fopen("newfile.txt", "w") or die("Unable to open file!");
file_put_contents('newfile.txt', $data);
$output = ob_get_clean();
$outputFile = "newfile.txt";
fwrite($handlefile, $output);
fclose($handlefile);
function MakeFileReadable($source , $export) {
$content = file_get_contents($source);
$x = explode (" " , $content);
$newx = "";
$count = 1;
foreach ($x as $word) {
$newx .= $word . " ";
if ($count %12 ==0) $newx .= "\r\n";
$count ++;
}
$fp = fopen("file-export.txt" , 'w');
if (!$fp) die("There is a problem with opening file...");
fwrite($fp , $newx);
fclose($fp);
}
MakeFileReadable("newfile.txt" , "file-export.txt");
?>
Use some array functions
$string = "one two three four five six seven eight nine ten eleven tweleve thirteen fourteen";
$arr = explode (" " , $string);
$lines = array_chunk($arr,4);
foreach($lines as $line)
echo implode (" ", $line)."\r\n";
result
one two three four
five six seven eight
nine ten eleven tweleve
thirteen fourteen
Here's a regex solution.
<?php
$test = 'one two three four five six seven eight nine ten eleven tweleve thirteen fourteen';
echo preg_replace('~((\w+\s){4})~', '$1' . "\n", $test);
Output:
one two three four
five six seven eight
nine ten eleven tweleve
\w is a word character (Alphanumeric characters plus "_", http://en.wikipedia.org/wiki/Regular_expression), if you only want A-Z use [a-z] and use the i modifier to make it case insensitive, ~((\w+\s){4})~i. The \s is a whitespace and the {4} is requiring 4 occurrences of the \w+\s.
Per your code...
$data = preg_replace('~((\w+\s){4})~', '$1' . "\n", $data);
file_put_contents('new_text_file.txt', $data);
http://php.net/manual/en/function.file-put-contents.php
Per updated code:
<?php
require "simple_html_dom.php";
$html = file_get_html("http://www.lipsum.com/");
$data = array();
$counter = 0;
foreach($html->find("div") as $tr){
$row = array();
foreach($tr->find("div") as $td){
$row[] = $td->plaintext;
}
$data[] = $row;
}
$data = preg_replace('~((\w+\s){4})~', '$1' . "\n", implode(' ', $data));
file_put_contents('new_text_file.txt', $data, FILE_APPEND | LOCK_EX);
Finally tested code:
<?php
function MakeFileReadable($source , $export) {
$content = file_get_contents($source);
$x = explode (" " , $content);
sort($x);
$newx = "";
$count = 1;
foreach ($x as $word) {
$newx .= $word . " ";
if ($count %4 ==0) $newx .= "\r\n";
$count ++;
}
$fp = fopen($export , 'w');
if (!$fp) die("There is a problem with opening file...");
fwrite($fp , $newx);
fclose($fp);
}
MakeFileReadable("file-input.txt" , "file-export.txt");

PHP Parsing a .dat file

I have a .dat file that is essentially ; delimited file and I'm trying to convert it to a tab delimited .txt. The problem that I am not sure about is that each row of the new file will be a combination of 3 of the original file's rows, each original row has a different quantity of data. The first column just identifies each row in a grouping. What would be the best way to do this?
Sample original data:
01;zxc;asd;qwe;uio;jkl;asd;123;456
02;lkj;oiu;oji
03;fjifao;vbofekjf;fjieofk;aoijf;voien3984
01;lkj;oiu;fji;eoj;vnk;fji;098;321
02;fji;oje;jvi
03;jie;voi;djv;eojf;38723
End output:
zxc asd qwe uio jkl asd 123 456 lkj oiu oji fjifao vbofekjf fjieofk aoijf voien3984
lkj oiu fji eoj vnk fji 098 321 fji oje jvi jie voi djv eojf 38723
Any ideas?
Here's how I'd do it:
$lines = file($data);
$rows = array();
$row_pivot = -1;
foreach ($lines as $line) {
// Split line by ;
$data = explode(';', trim($line));
// Get the first element
$r_id = array_shift($data);
if ($r_id == '01') {
// When 01 is the first element, start a new row
// You can dump the previous row here as well if you aim for speed
$row_pivot++;
$rows[$row_pivot] = array();
}
// Add data to row
$rows[$row_pivot] = array_merge($rows[$row_pivot], $data);
}
// Print rows
foreach ($rows as $r) {
echo implode("\t", $r)."\n";
}
I would personally explode the data then foreach row in the resulting array, then again explode each line at your delimiter ';' and then format an output that is tab delimited.
<?php
$data = 'LOADED FILE DATA';
$lines = preg_split( '/\r\n|\r|\n/', $data);
$out = '';
foreach($lines as $line){
$parts = explode(';',$line);
foreach($parts as $part){
$out .= $part.'\t';
}
$out .= '\n';
}
echo $out;
?>
code untested.
Should be something like this
$lines = file($filename);
$lineCount = count($lines);
$output = '';
for ($i = 0; $i < $lineCount - 2; $i += 3) {
$newLines = array();
for ($j = $i; $j < $i + 3; $j++) {
list($_, $rest) = explode(';', isset($lines[$j]) ? $lines[$j] : '');
$newLines = array_merge($newLines, $rest);
}
$output .= implode("\t", $newLines) . "\n";
}

PHP - parsing a txt file

I have a .txt file that has the following details:
ID^NAME^DESCRIPTION^IMAGES
123^test^Some text goes here^image_1.jpg,image_2.jpg
133^hello^some other test^image_3456.jpg,image_89.jpg
What I'd like to do, is parse this ad get the values into a more readable format, possibly into an array if possible.
Thanks
You can do that easily this way
$txt_file = file_get_contents('path/to/file.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
foreach($rows as $row => $data)
{
//get row data
$row_data = explode('^', $data);
$info[$row]['id'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
$info[$row]['images'] = $row_data[3];
//display data
echo 'Row ' . $row . ' ID: ' . $info[$row]['id'] . '<br />';
echo 'Row ' . $row . ' NAME: ' . $info[$row]['name'] . '<br />';
echo 'Row ' . $row . ' DESCRIPTION: ' . $info[$row]['description'] . '<br />';
echo 'Row ' . $row . ' IMAGES:<br />';
//display images
$row_images = explode(',', $info[$row]['images']);
foreach($row_images as $row_image)
{
echo ' - ' . $row_image . '<br />';
}
echo '<br />';
}
First you open the text file using the function file_get_contents() and then you cut the string on the newline characters using the function explode(). This way you will obtain an array with all rows seperated. Then with the function array_shift() you can remove the first row, as it is the header.
After obtaining the rows, you can loop through the array and put all information in a new array called $info. You will then be able to obtain information per row, starting at row zero. So for example $info[0]['description'] would be Some text goes here.
If you want to put the images in an array too, you could use explode() too. Just use this for the first row: $first_row_images = explode(',', $info[0]['images']);
Use explode() or fgetcsv():
$values = explode('^', $string);
Or, if you want something nicer:
$data = array();
$firstLine = true;
foreach(explode("\n", $string) as $line) {
if($firstLine) { $firstLine = false; continue; } // skip first line
$row = explode('^', $line);
$data[] = array(
'id' => (int)$row[0],
'name' => $row[1],
'description' => $row[2],
'images' => explode(',', $row[3])
);
}
By far the best and simplest example of this I have come accross is quite simply the file() method.
$array = file("myfile");
foreach($array as $line)
{
echo $line;
}
This will display all the lines in the file, this is also applicable for a remote URL.
Simple and clear.
REF : IBM PHP Parse
I would like to contribute a file that provides atomic data structures.
$lines = file('some.txt');
$keys = explode('^', array_shift($lines));
$results = array_map(
function($x) use ($keys){
return array_combine($keys, explode('^', trim($x)));
},
$lines
);
Try fgetcsv() with ^ as the separator character:
$file = fopen($txt_file,"r");
print_r(fgetcsv($file, '^'));
fclose($file);
http://www.w3schools.com/php/func_filesystem_fgetcsv.asp
<?php
$row = 1;
if (($handle = fopen("test.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "^")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
Ok, didn't see the edited version, so here's a redo. It's most likely a CSV file that uses carets as the separator, so...
$fh = fopen('yourfile.txt');
$headers = fgetcsv($fh, 0, '^');
$details = array();
while($line = fgetcsv($fh, 0, '^')) {
$details[] = $line;
}
fclose($fh);
youse a list, and split the "image_1.jpg,image_2.jpg" after you explode the string:
list($number, $status, $text, $images) = explode("^", $data);
$splited_images= preg_split(',', $images);
My solution
function parseTextFile($file){
if( !$file = file_get_contents($file))
throw new Exception('No file was found!!');
$data = [];
$firstLine = true;
foreach(explode("\n", $file) as $line) {
if($firstLine) {
$keys=explode('^', $line);
$firstLine = false;
continue;
} // skip first line
$texts = explode('^', $line);
$data[] = array_combine($keys,$texts);
}
return $data;
}

Categories