How to turn a text file into an array with php? - php

I have a text file like this:
filter 'no'
interval '15'
phonenumbers ''
color 'purple'
version '24/10/2016'
And I want to turn in into an array so when I do $array['filter'] the output should be no and when I do $array['color'] the output should be purple here's what I've tried so far:
<?php
$txt_file = file_get_contents('/home/ab/mytext.txt');
$rows = explode("'", $txt_file);
var_dump($rows);
?>
But it doesn't work, how can I do this ?

You should just put it into CSV format, and make the first token the key and the second token the value.
filter, no
interval, 15
Then just explode by new line and parse
$file = file_get_contents(...);
$lines = explode($file, "\n");
foreach($lines as $line) {
$l = str_getcsv($line);
// assign stuff to array
}

Try this:
$txt_file = file_get_contents('/home/ab/mytext.txt');
// explode to lines
$rows = explode( PHP_EOL, $txt_file);
$result = array();
foreach( $rows as $row ){
// explode each line by space
$parts = explode( ' ', $row );
// set values of arrray
$result[ $parts[0] ] = trim( $parts[1], '\'' );
}
echo $result['color'];

PHP's built-in file function can get file contents into array. Each value in the array is the corresponding line in the file. Explode each line into an array based on the space delimiter. This is the code you might be looking for:
<?php
$txt_file = file('/home/ab/mytext.txt', FILE_IGNORE_NEW_LINES);
foreach($txt_file as $value) {
$value_exploded = explode(' ', $value);
$arr[$value_exploded[0]] = $value_exploded[1];
}
var_dump($arr);
echo $arr['filter'];
?>
Hope it helps!

Related

array_diff doesn't work (PHP)

I have 2 array in my code, like the shown below:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
for($i=0;$i<$count;$i++){
for($j=0; $j<1; $j++){
$stopword[$i] = $stoplist[$i][$j];
}
}
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
var_dump($hasilfilter);
?>
$stopword contain of some stop word like attached in http://xpo6.com/list-of-english-stop-words/
All I wanna do is: I want to check if save the element that exist in array $kata and it is not exist in array $stopword
So I want to delete all the element that exist in both array $kata and $stopword .
I read some suggestion to use array_diff , but somehow it doesn't work to me. Really need your help :( Thanks.
array_diff is what you need, you are right. Here is a simplified version of what you try to do:
<?php
// Your string $kalimat as an array of words, this already works in your example.
$kata = ['I', 'just', 'want', 'to', '...'];
// I can't test $stopword code, because I don't have your file.
// So let's say it's a array with the word 'just'
$stopword = ['just'];
// array_diff gives you what you want
var_dump(array_diff($kata,$stopword));
// It will display your array minus "just": ['I', 'want', 'to', '...']
You should also double check the value of $stopword, I can't test this part (don't have your file). If it does not work for you, I guess the problem is with this variable ($stopword)
There is a problem in your $stopword array. var_dump it to see the issue.array_diff is working correct.
Try following code I wrote to make your $stopword array right:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
$stopword= call_user_func_array('array_merge', $stoplist);
$new = array();
foreach($stopword as $st){
$new[] = explode(' ', $st);
}
$new2= call_user_func_array('array_merge', $new);
foreach($new2 as &$n){
$n = trim($n);
}
$new3 = array_unique($new2);
unset($stopword,$new,$new2);
$stopword = $new3;
unset($new3);
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
print "<pre>";
var_dump($hasilfilter);
print "</pre>";
?>
I hope it helps

Converting CSV file with column seperator to JSON

I have a CSV file (my_data.csv) that I want to convert to JSON object.
With column ";" it gives me wrong result, with comma "," it works fine.
But I don't want edit the csv file. And I don't want use str_replace because the csv file is huge and it will take longer.
How can I change my conversion function to generate the correct JSON format ?
Here is my CSV file:
"Timestamp";"Longitude";"Latitude";"Client";"Price"
"2015-08-01 05:10:13";10.714069;48.031952;"test1";17.2
"2015-08-01 05:10:13";10.714069;48.031952;"test2";17.2
"2015-08-01 05:10:13";10.714069;48.031952;"test3";17.2
"2015-08-01 05:10:13";10.714069;48.031952;"test4";17.2
This is my PHP code
$file="data/my_file.csv";
$csv= file_get_contents($file);
$rows = explode("\n", trim($csv));
$data = array_slice($rows, 1);
$keys = array_fill(0, count($data),$rows[0] );
$json = array_map(function ($row, $key) {
return array_combine(str_getcsv($key), str_getcsv($row));
}, $data, $keys);
$data=json_encode($json);
echo $data;
I get this :
[{"Timestamp;\"Longitude\";\"Latitude\";\"Client\";\"Price\"":"2015-08-01 05:10:13;10.714069;48.031952;\"test1\";17.2"},
{"Timestamp;\"Longitude\";\"Latitude\";\"Client\";\"Price\"":"2015-08-01 05:10:13;10.714069;48.031952;\"test2\";17.2"},
{"Timestamp;\"Longitude\";\"Latitude\";\"Client\";\"Price\"":"2015-08-01 05:10:13;10.714069;48.031952;\"test3\";17.2"},
{"Timestamp;\"Longitude\";\"Latitude\";\"Client\";\"Price\"":"2015-08-01 05:10:13;10.714069;48.031952;\"test4\";17.2"}]
It should be this :
[{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test1","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test2","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test3","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test4","Price":"17.2"}]
You have to change
return array_combine(str_getcsv($key), str_getcsv($row));
to
return array_combine(str_getcsv($key, ';'), str_getcsv($row, ';'));
Because the default value of parameter $delimiter is ',':
array str_getcsv ( string $input [, string $delimiter = "," [, string
$enclosure = '"' [, string $escape = "\" ]]] )
Alternative solution:
<?php
$csvString = file_get_contents('/path/to/data.csv');
$csvRows = str_getcsv($csvString, "\n"); // split new lines, gives you rows
$rows = array();
foreach($csvRows as $row) {
$rows[] = str_getcsv($row, ";"); // parse the rows
}
// remove the first row. its the CSV column heading line. keep keys for reuse.
$itemKeys = array_shift($rows);
// run over all rows and combine keys with values, to get a named array
foreach($rows as $rowKeys => $rowValues) {
$array[] = array_combine($itemKeys, $rowValues);
}
echo json_encode($array);
Result:
[{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test1","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test2","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test3","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test4","Price":"17.2"}]

PHP: Sort array by exploded value

How can I sort an array by a value from an exploded string?
To make it a bit more clear, I have data stored in a textfile in the following format:
Value_1|Value_2|Value_3|Value_4|Value_5
Value_1|Value_2|Value_3|Value_4|Value_5
Value_1|Value_2|Value_3|Value_4|Value_5
...
I read the data using
$data_file = 'foo.txt';
$lines = file($data_file, FILE_IGNORE_NEW_LINES);
then explode each line and output the content (HTML stripped to keep it clean)
foreach ($lines as $line_num => $dataset) {
$dataset = explode('|', $dataset);
//echo exploded values + some HTML
}
However, before I output the data, I want to sort the array by Value_2 (which is always a number) from e.g. high to low. Do I have to set the keys of the array to Value_2 and then sort it? How can I do that? What would be the best solution here?
Thanks for your help!
This is the final, slightly modified snippet for everyone who's interested:
$data_file = 'foo.txt';
$lines = file($data_file, FILE_IGNORE_NEW_LINES);
function sort_data_array($a, $b){
$ex_a = explode('|', $a);
$ex_b = explode('|', $b);
if ($ex_a[1] == $ex_b[1]) {return 0;}
return ($ex_a[1] > $ex_b[1]) ? -1 : 1;
}
uasort($lines, 'sort_data_array');
$lines = array_values($lines);
foreach ($lines as $line_num => $dataset) {
//output
}
Use a custom sort function:
EG:
uasort ($lines, function($a , $b)) {
$ex_a = explode('|', $a);
$ex_b = explode('|', $b);
// change the < to > if they are in reverse...
return (strcmp($ex_a[1], $ex_b[1]) < 0 ? 1: -1);
}
print_r($lines);
Here is a method without a custom sort function.
This can be refactored if the number of columns is unknown.
<?php
$raw_records = 'Value_1|2|Value_3|Value_4|Value_5
Value_1|5|Value_3|Value_4|Value_5
Value_1|3|Value_3|Value_4|Value_5';
$records = array();
$lines = explode("\n", $raw_records);
foreach ($lines as $line_num => $dataset) {
$dataset = explode('|', $dataset);
$records[$dataset[1]][] = $dataset[0];
$records[$dataset[1]][] = $dataset[2];
$records[$dataset[1]][] = $dataset[3];
$records[$dataset[1]][] = $dataset[4];
}
ksort($records, SORT_NUMERIC);
echo '<pre>'; var_dump($records); echo '</pre>';
?>

find and replace a specific string of a a particular line in txt file with php

I want to know that how can I replace a specific word/string of a particular line into a text file with php.
Contents of text file is as below:
1|1|1
nikki|nikki#yahoo.com|nikki
nikki|nikki#gmail.com|nikki
nikki|nikki#hotmail.com|nikki
DETAILS OF FIELDS:
COLUMN:0 = $name,
COLUMN:1 = $email,
COLUMN:2 = $nickname,
DETAILS OF REPLACEMENT:
COLUMN:0 = $newName,
COLUMN:1 = $newEmail,
COLUMN:2 = $newnickName,
From the above content you can guess that the find/search is based on the column:1. Ans if match found, than replace the column:0 OR column:2 [based on the choice].
I tried [for finding the column:1]:
$fileData = file("file.txt");
foreach($fileData as $Key => $Val) {
$Data[$Key] = explode("|", $Val);
if ( trim($Data[$Key][1]) == $email ){
unset($fileData[$Key]);
//REPLACE TAKE PLACE HERE
break;
}
}
[for replace]:
/* REPLACE NAME */
$file = "file.txt";
$oname = "|$name|";$nname = "|$newName|";
file_put_contents($file, str_replace($oname, $nname, file_get_contents($file)));
/* REPLACE NICKNAME */
$file = "file.txt";
$onickname = "|$nickname|";$nnickname = "|$newnickname|";
file_put_contents($file, str_replace($onickname, $nnickname, file_get_contents($file)));
But it was replacing all the matching "$name".
I also tried in the following way:
$fileData[$Key] = str_replace($name, $newName, $fileData[$Key]);
file_put_contents($file,$fileData);
/* $name & $newName -:> $nickname & $newnickname
But it doesn't works.
If i want to replace column:0 ["nikki"] of "nikki#gmail.com" with "nikkigmail", then the data should be:
1|1|1
nikki|nikki#yahoo.com|nikki
nikkigmail|nikki#gmail.com|nikki
nikki|nikki#hotmail.com|nikki
And, if want to replace column:2 ["nikki"] of "nikki#hotmail.com" with "hotmail", then:
1|1|1
nikki|nikki#yahoo.com|nikki
nikkigmail|nikki#gmail.com|nikki
nikki|nikki#hotmail.com|hotmail
May i get the code to be corrected ?
Here is how I would replace something like this. Instead of worrying about str_replace, why not actually modify the array returned by file?
<?php
$email = "nikki#gmail.com"; // Search email
$data = file("file.txt", FILE_IGNORE_NEW_LINES); // Read in the data
foreach($data as $key => $line) {
$bits = explode("|", $line);
if($bits[1] === $email) {
// Update this in place,
$bits[0] = "nikkigmail";
$data[$key] = implode("|", $bits);
}
}
$write = implode("\n", $data); // the data to write however you please.
Keep in mind this can also be expanded to suit your row/column needs. For example, you could use something like this.
/**
* The reason these are named differently is because they don't always
* search/replace. For example, you can find nikki#gmail.com in one row,
* but just be setting a different column in that row to a value..
*/
$match = array('col' => 1, 'str' => 'nikki#gmail.com'); // Search data at row
$update = array('col' => 0, 'str' => 'nikkigmail'); // Replace data at row
$data = file("file.txt", FILE_IGNORE_NEW_LINES); // Read in the data
foreach($data as $key => $line) {
$bits = explode("|", $line);
if($bits[$match['col']] === $match['str']) {
// Update this in place,
$bits[$update['col']] = $update['str'];
$data[$key] = implode("|", $bits);
}
}
$write = implode("\n", $data); // the data to write however you please.

str_getcsv into a multidimensional array in php

I have csv values like this:
$csv_data = "test,this,thing
hi,there,this
is,cool,dude
have,fun";
I want to take an entire CSV string and read it into a multidemensional array so that I get:
array(
array(
'test' => 'hi',
'this' => 'there',
'thing' => 'this'
),
array(
'test' => 'is',
'this' => 'cool',
'thing' => 'dude'
),
array(
'test' => 'have',
'this' => 'fun',
'thing' => ''
)
);
I want an output like that, take note that the CSV value is dynamic.
Assuming every row in the CSV data has the same number of columns, this should work.
$lines = explode("\n", $csv_data);
$head = str_getcsv(array_shift($lines));
$array = array();
foreach ($lines as $line) {
$array[] = array_combine($head, str_getcsv($line));
}
If lines have a variable number of columns (as in your example, where the last line has 2 columns instead of 3), use this loop instead:
foreach ($lines as $line) {
$row = array_pad(str_getcsv($line), count($head), '');
$array[] = array_combine($head, $row);
}
Here is a complete solution:
$lines = explode("\n", $csv_data);
$formatting = explode(",", $lines[0]);
unset($lines[0]);
$results = array();
foreach ( $lines as $line ) {
$parsedLine = str_getcsv( $line, ',' );
$result = array();
foreach ( $formatting as $index => $caption ) {
if(isset($parsedLine[$index])) {
$result[$formatting[$index]] = trim($parsedLine[$index]);
} else {
$result[$formatting[$index]] = '';
}
}
$results[] = $result;
}
So what are we doing here?
First, your CSV data is split into array of lines with explode
Since the first row in your CSV describes data format, it must be separated from the actual data rows (explode and unset)
For storing the results, we initialize a new array ($results)
Foreach is used to iterate through the data line by line. For each line:
Line is parsed with PHP's str_getcsv
An empty result array is initialized
Each line is inspected in the light of the format. Cells are added and missing columns are padded with empty strings.
Here is a very clean and simple solution:
function parse_row($row) {
return array_map('trim', explode(',', $row));
}
$rows = str_getcsv($csv_data, "\n");
$keys = parse_row(array_shift($rows));
$result = array();
foreach ($rows as $row) {
$row = parse_row($row);
$row = array_pad($row, 3, NULL);
$result[] = array_combine($keys, $row);
}

Categories