PHP get a string into a associative array - php

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.

Related

Deleting/replacing data inside text file

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 "

Change Plain Text To JSON Array

I am getting the following data from a file_get_contents php://input
transfer_date:2018-02-14 content:1000_102eabca374092d1e97daf0bf52e9d count:1
transfer_date:2018-02-13 content:1000_1022e2297c8e9e1a18743182e4f265 count:0
transfer_date:2018-02-13 content:1000_10254e35fda57121d48bd71693c500 count:0.5
transfer_date:2018-02-12 content:102ead3122a4c8742bff97fcc46b38 count:0.5
transfer_date:2018-02-12 content:1000_102ee58d8e12eadbce86d526607164 count:0.5
Any ideas on how to turn this into a json array?
I want the data in format
"transfer_date":"2018-02-14","content":"123445585989898","count":"1"
so I can run it through a for each.
I have tried on the values but it only gets me halfway there and I can keep using find replace but there must be another way no?:
//$datatwo = str_replace('transfer_date: '"transfer_date":"',"$datatwo");
You can use regex to get not-space symbols before and after colon
$arr = array_map(function($x) {
if (preg_match_all('/(\S+):(\S+)/',$x, $m)) {
return array_combine($m[1], $m[2]);
}
}, file('php://stdin', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
echo json_encode($arr, JSON_PRETTY_PRINT);
demo
i'm not sure, but i guess this would work for you.
<?php
$input = file('php://stdin', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$transfers = [];
foreach($input as $line) {
$transfer=[];
// break the white space between key=value so each key/value get added alone
$parts = explode(' ',$line);
foreach($parts as $part) {
// separate the key and value
$values=explode(':',$part);
$transfer[ $values[0] ] = $values[1] ?? null;
}
// add to the result
$transfers[]= $transfer;
}
// print json encoded result
echo json_encode($transfers);
Simpliest you could do if the there are only spaces between fields and colons as key/value separator:
$data = ''; //your data
$data = str_replace("\r\n", "\n", $data); //remove carriage return
$lines = array_filter(explode("\n", $data)); //split your data by new line and filter empty lines
$rows = [];
foreach ($lines as $line) {
$fields = explode(' ', $line); //explode the content of a line by space to get all fields
foreach ($fields as $field) {
$fieldParts = explode(':', $field); //explode a field to get key and value
$rows[$fieldParts[0]] = $fieldParts[1]; //assign it to your result array
}
}
var_dump(json_encode($rows));

How to read specific lines from a text file in PHP

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.

How can I divide data separated by commas on different lines

I have this script that extracts a .csv file from the database that holds data for different locals that a user has logged into. The .csv files come like this:
"id_user";"id_local"
"1";""
"2";"2,3,4"
"3";""
"5";"2,5"
"10";""
"13";"2"
"14";"5"
"15";"2"
"16";"1"
"20";"2"
"21";""
As you can se, it get one register per user
But, to manipulate it properly, we need it like this:
"id_user";"id_local"
"2";"2"
"2";"3
"2";"4"
"5";"2"
"5";"5"
"13";"2"
"14";"5"
"15";"2"
"16";"1"
"20";"2"
So, I need to create a function that deletes users with no local and splits different locals of the same user in different registers. Does anyone knows how can I do it?
Here is the code I have so far but I'm not sure if I'm on the right way:
function fix_local_secundario(){
$filename = "local_secundario.csv";
$file_locais = file_get_contents($filename);
$locais = explode("\n", $file_locais);
// $pattern = "/,/";
// $replacement = "\"\n;\"";
while ($line = current($locais)) {
$line = str_getcsv($line, ';', '"','\n');
// $line = preg_replace($pattern, $replacement, $line);
var_dump($line);
echo "\n";
next($locais);
}
}
Try this and see if this works:
function fix_local_secundario(){
$filename = "local_secundario.csv";
$file_locais = file_get_contents($filename);
$locais = explode("\n", $file_locais);
while ($line = current($locais)) {
// do first split on ; character
$arr1 = explode(";", $line);
// if the part after ; is not empty for this line
if ($arr1[1]!='""'){
// split it further on , character
$arr2 = explode(",", $arr1[1]);
foreach ($arr2 as $key => $val){
if($val[0] != '"'){
$val = '"'.$val;
}
if($val[strlen($val)-1] != '"'){
$val = $val . '"';
}
echo $arr1[0] . ";" . $val . "<BR>";
}
}
next($locais);
}
}
Once this basic piece is working, you should change it to return values rather than echo values since this code is part of a function as per updates made to your question.
What about this…
$f = fopen("myfile.csv", "r");
while($row = fgetcsv($f, 0, ";")){
$locals = explode(",", $row[1]);
if (count($locals)>1){
foreach($locals as $local)
// iterate with $row[0] and $local
}elseif($row[1] != "")
// use $row[0] and $row[1]
}

parsing a text file in php and retrieving information

I'm trying to parse a basic text file in PHP, but not sure where to begin.
The file contains info such as:
http://pastebin.com/ahqtJzH6
You'll notice that the information I need to capture is split up by new lines. Right now I'm just throwing every new line into a $applicant[] array, but I need to get rid of the preceding text in each line.
I was thinking I probably need to use regex or something to single out just the data I need. Ideas?
Thank you!
Without using regex, you can do this:
$fp = fopen('textfile.txt', 'r');
$return = array();
while ($line = fgets($fp)) {
$parts = explode(':', $line);
$key = trim($parts[0]);
unset($parts[0]);
$value = str_replace("\n", '', implode(':', $parts));
$return[$key] = trim($value);
}
print_r($return);
Would output something like:
Array (
[Applicant SSN] => 123456789
[Applicant Name] => BOB, BOB
...
)
You could use strpos to find the : character and then grab everything after that. You can use trim to get rid of extra whitespace.
$lines = file('textfile.txt');
foreach ($lines as $line) {
$p = strpos($line, ':');
if ($p!==false) {
$key = trim(substr($line, 0, $p));
$value = trim(substr($line, $p+1));
// do whatever with your key & value
}
}

Categories