I have a txt file which has a lot of lines and the values in every line are separated with commas.
I want to read the 1st line alone which I did already using fgets :
$head = fgets(fopen($file, 'r'));
$headValues = explode(',', $head);
but now I want to read every other line from line 2 until the end of file and put those values into an array.
I searched for similar solutions but couldn't find any
Just use descriptor
$fd = fopen($file, 'r');
$head = fgets($fd);
$headValues = explode(',', $head);
$data = [];
while(($str = fgets($fd)) !== false) {
$otherValues = explode(',', $str);
$data[] = $otherValues;
}
This uses fgetcsv for the lines you care about and uses array_combine to put the headers and the line data together.
$fh = fopen($file, 'r');
$headValues = fgetcsv($fh);
$data = [];
while (true) {
if ( ($values = fgetcsv($fh)) === false ) {
break;
}
$data[] = array_combine($headValues, $values);
if ( fgets($fh) === false ) {
break;
}
}
fclose($fh);
print_r($data);
It checks at each read in case the EOF has been reached and then breaks out of the read loop.
You could use file(), array_map() and array_shift() :
$lines = file($file) ; // get file as array.
$lines = array_map(function($l){ return explode(',', $l); }, $lines);
$headValues = array_shift($lines); // get first values (removed from $lines)
So, $lines will contains all lines except the first one.
Related
I want to do if conditional between text data and variable data then delete the line
Example
I have a txt data with usernames like ( one two one three one) every user in line,
And i want to delete all data except "one" username
My Code;
if(file_get_contents('visitors.txt') != "one") {
$GetLine = ;
function removeLine ($url, $lineToRemove)
{
$data = file_get_contents($url);
$lines = explode(PHP_EOL, $data);
$lineNo = 1;
foreach($lines as $line)
{
$linesArray[$lineNo] = $line;
$lineNo++;
}
unset($linesArray[$lineToRemove]);
return implode("\n", $linesArray);
}
$data = removeLine ("username.txt", $getLine);
echo $data
}
the function is used to remove lines.
My problem is doing if with the data + $getLine number, I just want to remove all the lines except line that has one word.
Can simply do it with a regular expression:
$file = preg_grep('#one#', file('file.txt'));
This will make $file an array holding only lines containing the string "one". To turn the array back into a string, you just implode it.
If you only want to echo the lines containing "one", you can also use iterators:
$file = new RegexIterator(new SplFileObject("file.txt"), '#one#');
foreach ($file as $content) {
echo $content, PHP_EOL;
}
This will go over the file line by line and echo any line having the string one in it. The benefit is that it doesn't use two arrays as intermediate structures.
Just a note, you shouldn't be defining functions inside an if statement.
Also, unless I'm misunderstanding, you shouldn't even need line numbers.
function remove_line( $data, $remove ){
$lines = explode( PHP_EOL, $data ); // Convert to Array
$new_lines = ''; // Start a new variable we'll add to in a loop
foreach( $lines as $line ){
$line = trim( $line ); // Trim Whitespace
if( $line != $remove ){
// Line isn't a line we want removed, so save it plus an EOL
$new_lines .= $line.PHP_EOL;
}
}
return $new_lines;
}
Now if you load in a file like so: $file = file_get_contents( 'my-file.txt' ); that contains the following:
One
Two
One
Three
One
Once you run it through the remove_line function, you'll end up something like:
$file = file_get_contents( 'my-file.txt' );
$new_file = remove_line( $file, 'One' );
var_dump( $new_file ); // Returns: string(10) "Two Three "
I am reading a txt file on the following way:
$handle = fopen($captionTextFile, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo ($line);
}
fclose($handle);
}
// Output
IMAG0986.jpg|Title something 1 here|<b>Description</b><br />You can use HTML as you can see!
IMAG0988.jpg|Title something 2 here|<b>Description</b><br />You can use HTML as you can see!
etc...
Now I want to store only the values between the first | by line in a php array. Example of what I intend to have:
$json = '{"IMAG0986.jpg": "Title something 1 here",
"IMAG0988.jpg": "Title something 2 here"}';
In order to access this array later in this way:
$obj = json_decode($json);
print $obj->{'IMAG0986.jpg'}; // print: "Title something 1 here"
The problem that I'm having is how do I pass the values from the lines to the array? any help please?
Use file() to read the file lines to an array, then use explode() with | delimiter and add the 1st part as key and 2nd as value to an array, finally use json_encode().
Something like:
<?php
$captionTextFile = "test.pipe";
$arrayFinal = array();
$lines = file($captionTextFile);
foreach($lines as $line) {
$array = explode("|", $line);
$arrayFinal[$array[0]] = $array[1];
}
print_r(json_encode($arrayFinal));
//{"IMAG0986.jpg":"Title something 1 here","IMAG0988.jpg":"Title something 2 here"}
//If you don't need json, just access the array by key:
echo $arrayFinal['IMAG0986.jpg'];
//Title something 1 here
You can explode() the lines into keys and values in an object to achieve that desired JSON result.
$data = new stdClass();
$handle = fopen($captionTextFile, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$row = explode('|', $line);
$data->{$row[0]} = row[1];
}
fclose($handle);
}
json_encode($data);
I am trying to put a new data "exemple" for each line of the CSV. The lines of the csv varies. The header column name would be ExempleRow
There is not separator only a delimiter which is the semi colon.
I'm using fputcsv, it must have an array to fill the csv file with desired data. But in my case the number of lines changes for each csv.
So far it adds the new column with but I can't understand how to put the same value in each line for that column ?
<?php
$newCsvData = array(); // here should I specify the same data value "exemple data" for each line ? but how ?
if (($handle = fopen("exemple.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 9999, ";")) !== FALSE) {
$data[] = 'ExempleRow';
$newCsvData[] = $data;
}
fclose($handle);
}
$handle = fopen('exemple.csv', 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line,';',' ');
}
fclose($handle);
?>
If you want to show the keys of the array as the first column then you can do this. If you dont have an associative array or you want to hard code the column headers for what ever reason you can simply change the array_keys($line) for a hard coded array.
$handle = fopen('exemple.csv', 'w');
$keys = false;
foreach ($newCsvData as $line) {
if ($keys === false) {
//$header = array('HeaderOne', 'HeaderTwo', 'HeaderThree', 'HeaderFour'); Use this if you want to hard code your headers
fputcsv($handle, array_keys($line), ';', '');
$keys = true;
}
fputcsv($handle, $line,';',' ');
}
fclose($handle);
I've got a variable going like this(in the original list there no whitespace):
http://www.iso.org/iso/list-en1-semic-3.txt
$country ="
ÅLAND ISLANDS;AX
ALBANIA;AL
ALGERIA;DZ
";
(going on and on in the same order)
I like to put this in a array going like this:
array: [Åland Islands] ==> AX
[Albania] ==> AL
[Algeria] ==> DZ
I've try to use php explode but that doesn't work, my knowledge is to basic to get it right. Who can help?
print_r(explode(';', $country));
This will get you where you're going:
$output = array();
// break it line-by-line
$lines = explode('\n', $country);
// iterate through the lines.
foreach( $lines as $line )
{
// just make sure that the line's whitespace is cleared away
$line = trim( $line );
if( $line )
{
// break the line at the semi-colon
$pieces = explode( ";", $line );
// the first piece now serves as the index.
// The second piece as the value.
$output[ $pieces[ 0 ] ] = $pieces[ 1 ];
}
}
$result = array();
$lines = explode(PHP_EOL, $country);
foreach ($lines as $line) {
$line = explode(';', $line);
$result[array_shift($line)] = array_shift($line);
}
$a = explode("\n", $country);
$result = array();
foreach($a as $line) {
list($x,$y) = explode(";", $line);
$result[$x] = $y;
}
Note: remove extra empty lines from $country or check for empty lines.
I need to read the data from a file that can be either comma or tab delimited. I now that there is a function getcsv but it accepts only one possible delimiter.
Any ideas how to handle this?
Thanks.
Starting from PHP 5.3, you can use str_getcsv() to read individual lines using different delimiters.
$someCondition = someConditionToDetermineTabOrComma();
$delimiter = $someCondition ? "," : "\t";
$fp = fopen('mydata.csv', 'r');
while ( !feof($fp) )
{
$line = fgets($fp, 2048);
$data = str_getcsv($line, $delimiter);
doSomethingWithData($data);
}
fclose($fp);
You can specify a delimiter for fgetcsv(). This is an example of reading tab-delimited files,
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
...
}
Here is an example that will read mydata.txt CSV fields
$tab = "\t";
$fp = fopen('mydata.txt', 'r');
while ( !feof($fp) )
{
$line = fgets($fp, 2048);
$data_txt = str_getcsv($line, $tab);
//Get First Line of Data over here
print_r($data_txt);
exit;
}
fclose($fp);
$filePath = "somefile.txt";
$delimiter = "\t";
$file = new \SplFileObject($filePath);
while (!$file->eof()) {
$line = $file->fgetcsv($delimiter);
print_r($line);
}
Read the whole file, or line by line and split it using split.
There you can include a regex with arbitrary delimiters. I have not PHP here to test a statement, but php.net -> search for split().
There you also have a comment relating to regex.
you can try explode
explode ( string $delimiter , string $string [, int $limit ] );
Here is the function that I added to my utilities library for future use. I derived it from NSSec's answer.
This solution allows you to specify whether you want to use the first line as keys for the array. I will probably add the ability to pass an array to be used for keys for the $first_line_keys parameter at some point.
/**
* Converts a CSV file into an array
* NOTE: file does NOT have to have .csv extension
*
* $file - path to file to convert (string)
* $delimiter - field delimiter (string)
* $first_line_keys - use first line as array keys (bool)
* $line_lenght - set length to retrieve for each line (int)
*/
public static function CSVToArray($file, $delimiter = ',', $first_line_keys = true, $line_length = 2048){
// file doesn't exist
if( !file_exists($file) ){
return false;
}
// open file
$fp = fopen($file, 'r');
// add each line to array
$csv_array = array();
while( !feof($fp) ){
// get current line
$line = fgets($fp, $line_length);
// line to array
$data = str_getcsv($line, $delimiter);
// keys/data count mismatch
if( isset($keys) && count($keys) != count($data) ){
// skip to next line
continue;
// first line, first line should be keys
}else if( $first_line_keys && !isset($keys) ){
// use line data for keys
$keys = $data;
// first line used as keys
}else if($first_line_keys){
// add as associative array
$csv_array[] = array_combine($keys, $data);
// first line NOT used for keys
}else{
// add as numeric array
$csv_array[] = $data;
}
}
// close file
fclose($fp);
// nothing found
if(!$csv_array){
return array();
}
// return csv array
return $csv_array;
} // CSVToArray()