How can i convert txt file to array - php

I have this sort of structure on a txt file.
[FILE_INFO]
[FIRST]
LOAD1= CPU
LOAD2 = RAM
[END_FIRST]
[GLOBAL_INDEX]
ELEC1=1235.12
GAZ2,1=1563.123
GAZ2,2= 28.56
[END_GLOBAL_INDEX]
[END_FILE_INFO]
What i need is to convert this txt structure to a php array , is this possible or txt structure is know ?
Array
(
[FILE_INFO] => Array
(
[FIRST] => Array
(
[LOAD1] => CPU
[LOAD2] => RAM
)
[GLOBAL_INDEX] => Array
(
[ELEC1] => 1235.12
[GAZ2] => Array
(
[1] => 1563.123
[2] => 28.56
)
)
)
)
Here is my approach:
$txt_file = file_get_contents("test.rt");
$rows = explode("\n", $txt_file);
$new_array = array(); $dimension = array();
foreach($rows as $row =>$data)
{
if($data[0] == "[" && substr($data, 0, 4) != "[END"){ // start
$output = str_replace( array('[',']') , '' , $data );
array_push($dimension, trim($output));
continue;
}else if(substr($data, 0, 4) == "[END"){ // end
$output = str_replace( array('[',']') , '' , $data );
array_pop($dimension);
continue;
}
$dim="";
foreach($dimension as $k=>$v){
$dim.= "['$v']";
}
$new_array.$dim[] = $data; // this is not working !!!!!
}
The problem is to position my cursor in the dimension of the array and insert the data

Try this:
<?php
$myfile = fopen("test.txt", "r");
// Iterate one line until end-of-file
while(!feof($myfile)) {
$text[] = fgets($myfile); // Add the data in an array
}
fclose($myfile);
print_r($text); // print the array
?>

Related

How to dynamically get column value from csv file using php

i have two columns in csv file Name and Phone . If i given phone number as a variable $searchStr = "6059574150"; it has to find number in csv file and i need that contact name to get access dynamicaly like this $data['Name'] instead of $data['0']
MY php code
$header = array();
$final_result = array();
$file = fopen('example.csv', 'r');
if($file){
$row = 1;
while ($data = fgetcsv($file, 10000, ",")){
if($row == 1){
$header = array_values($data);
}
else{
$final_result[] = array_combine($header, array_values($data));
}
$row++;
}
}
echo "<pre>";
print_r($final_result);
my output is like this
Array
(
[0] => Array
(
[Names] => MICHAEL
[Phone] => 6059342614
)
[1] => Array
(
[Names] => GLENN
[Phone] => 6056296061
)
)
how to directly access column ? like this $data['Name']
If phone numbers are unique, you could do something like this:
<?php
$final_result = array();
$file = fopen('example.csv', 'r');
if($file) {
$header = fgetcsv($file, 10000, ",");
while ($data = fgetcsv($file, 10000, ",")) {
$final_result[$data[1]] = $data[0];
}
}
?>
If you have more than one name (person) for each phone number, you can concatenate them $final_result[$data[1]] .= ',' . $data[0];.
Example result:
array (
phone1 => 'name1',
phone2 => 'name2',
phone3 => 'name3',
)
To search a name from a phone number you have to do: $final_result[phone_number] and you get the name.
In your output array "$final_result" you can look for a Name by phone number this way:
$foundKey = array_search('pone_number_to_search', array_column($final_result, "Phone"));
$foundNames = $final_result[$foundKey]["Names"];

Reading values from a file which contains associative array PHP

I need to read the content of a file called orders.log with PHP and use the variables. The log file is stored like this:
Array
(
[time] => 2099-99-99 00:00:00
[gateway] => Paypal
[gatewayOK] => Yes
[gatewayTransactionId] => XXXXXXX
[POST] => Array
(
[mc_gross] => 9.99
[protection_eligibility] => Eligible
[address_status] => confirmed
[payer_id] => XXXXX
[address_street] => XXXXX
[payment_date] => 00:00:00 Nov 11, 2018 PDT
[payment_status] => Completed
[charset] => windows-1252
)
)
I have tried reading it like this:
<?php
$orders=file_get_contents("orders.log");
echo $orders['time'];
echo $myarray[0]['gateway'];
echo $myarray[1]['mc_gross'];
?>
But the result does not work like intended. It throws "A" and "r" . Any help would be appreciated.
This assumes that each entry is 20 lines long, it reads in the log file and the splits it into 20 segments using array_chunk().
It then processes each segment, first splitting the lines by the => using explode() and adding the values to an associative array with the left hand side as the key. You can then use the key to access each value.
$input = file("log.txt", FILE_IGNORE_NEW_LINES);
$orders = array_chunk($input, 20);
foreach ( $orders as $order ) {
$split = [];
foreach ( $order as $line ) {
$info = explode("=>", $line);
if ( count($info) == 2){
$split[trim($info[0]," \t[]")] = trim ($info[1]);
}
}
echo "gateway-".$split['gateway'].PHP_EOL;
echo "mc_gross-".$split['mc_gross'].PHP_EOL;
}
If you wanted a list of all orders...
$input = file("log.txt", FILE_IGNORE_NEW_LINES);
$orders = array_chunk($input, 20);
$orderList = [];
foreach ( $orders as $order ) {
$split = [];
foreach ( $order as $line ) {
$info = explode("=>", $line);
if ( count($info) == 2){
$split[trim($info[0]," \t[]")] = trim ($info[1]);
}
}
$orderList[] = $split;
}
echo "gateway-".$orderList[0]['gateway'].PHP_EOL;
echo "mc_gross-".$orderList[0]['mc_gross'].PHP_EOL;
A third way which doesn't rely on the data being all the same format, this reads on a line by line basis and tries to work out the end of an element itself (just a line containing ))...
$fp = fopen("log.txt", "r");
$orderList = [];
$order = [];
while ( $line = fgets($fp)) {
// Remove extra data after content
$line = rtrim($line);
// If end of order (a line just starting with a ')')
if ( $line == ')' ) {
// Convert order into associative array
$split = [];
foreach ( $order as $line ) {
$info = explode("=>", $line);
if ( count($info) == 2){
$split[trim($info[0]," \t[]")] = trim ($info[1]);
}
}
// Add data to order list
$orderList[] = $split;
$order = [];
}
else {
// Add line to existing data
$order[] = $line;
}
}
print_r($orderList);
fclose($fp);

PHP CSV to associative array with top row as keys and columns as value arrays

I am trying to create a multidimensional array using CSV file so that for example:
"a","b","c"
1,2,3
4,5,6
would return as:
array(
'a' => array(1, 4),
'b' => array(2, 5),
'c' => array(3, 6),
)
But the code I have:
<?php
function readCSV($csvFile) {
$aryData = [];
$header = NULL;
$handle = fopen($csvFile, "r");
if($handle){
while (!feof($handle)){
$aryCsvData = fgetcsv($handle);
if(!is_array($aryCsvData)){
continue;
}
if(is_null($header)){
$header = $aryCsvData;
}
elseif(is_array($header) && count($header) == count($aryCsvData)){
$aryData[] = array_combine($header, $aryCsvData);
}
}
fclose($handle);
}
return $aryData;
}
print_r(readCSV("Book1.csv"));
?>
Returns it as:
Array(
[0] => Array ( [a] => 1 [b] => 2 [c] => 3 )
[1] => Array ( [a] => 4 [b] => 5 [c] => 6 )
)
Would appreciate any help!
Instead of building the end array as you go along. This code reads the header row before the loop, then just reads all of the data lines into another array. It then combines each element of the header array with the matching column from the data array (using array_column() and the position of the header element)...
function readCSV($csvFile) {
$aryData = [];
$output = [];
$header = NULL;
$handle = fopen($csvFile, "r");
if($handle){
$header = fgetcsv($handle);
while ($aryData[] = fgetcsv($handle));
foreach ( $header as $key=>$label) {
$output[$label] = array_column($aryData, $key);
}
fclose($handle);
}
return $output;
}
Read the first row of the file and create the associative array with empty columns. Then read each remaining row and loop through it, pushing the values onto the column arrays.
<?php
function readCSV($csvFile) {
$aryData = [];
$handle = fopen($csvFile, "r");
if($handle){
$headerRow = fgetcsv($handle);
if (!$headerRow) {
return $aryData;
}
foreach ($headerRow as $colname) {
$aryData[$colname] = [];
}
while ($aryCsvData = fgetcsv($handle)){
foreach ($headerRow as $colname) {
$aryData[$colname][] = each($aryCsvData);
}
}
fclose($handle);
}
return $aryData;
}

Explode using 2 delimiter for a single line

i need to upload a .txt file in database.
my .txt file is exactly looks like
Name|Code|Email|Designation|Number|Salary|Age\t
syed|101|syed#gmail.com|trainee|7222877798|6000|21\t
hari|102|hari#gmail.com|trainee|9554512582|6000|23\t
i have need to separate it with | and then \t.
while getting array, the first one achieved as what i expect. but i cant able make \t explode.. can any one help me on this forum??
my routine is described below
if ($_POST['frmSubmit']) {
$file = $_FILES['frmUpload']['tmp_name']; // Get Temporary filename
$handle = fopen($file,"r"); // Open the file and read
while($strBookData = fgets($handle, 4096)) { // To get Array from .txt
$strDatas[] = $strBookData;
$strTableColumn = count($strBookData);
}
$strDatas = explode("|",implode($strDatas));
printArray($strDatas); exit;
if ($strDatas) {
$strInsertRecords = 0;
$strDuplicationRecords = 0;
if ($strTableColumn == 7) {
for($k=1; $k<count($strDatas); $k++) { //$k=1 is initialized because $k[0] is a header field array.
$strStatus = doCheckDuplication($strDatas[$k]['2']);
if ($strStatus == 0) {
// Insert Code
$strData = $strDatas[$k];
doInsertEmployeeDetails($strData['0'], $strData['1'], $strDatas[$k]['2'], $strData['3'], $strData['4'], $strData['5'], $strData['6']);
$strInsertRecords++; // To Get Inserted Records Count.
} else {
$strDuplicationRecords++; // To Get Duplication Records Count.
}
}
}
}
Hi this will split the text you provided.
$text = 'Name|Code|Email|Designation|Number|Salary|Age\t
syed|101|syed#gmail.com|trainee|7222877798|6000|21\t
hari|102|hari#gmail.com|trainee|9554512582|6000|23\t';
//remove line endings
$text = str_replace(array("\r\n", "\r", "\n"), "", $text);
$rows = explode('\t', $text);
$data = array();
foreach ($rows as $row){
//don't include empty lines
if(!empty( $row )){
$data[] = explode('|', $row);
}
}
echo '<pre>';
var_export( $data );
Outputs:
array (
0 =>
array (
0 => 'Name',
1 => 'Code',
2 => 'Email',
3 => 'Designation',
4 => 'Number',
5 => 'Salary',
6 => 'Age',
),
1 =>
array (
0 => 'syed',
1 => '101',
2 => 'syed#gmail.com',
3 => 'trainee',
4 => '7222877798',
5 => '6000',
6 => '21',
),
2 =>
array (
0 => 'hari',
1 => '102',
2 => 'hari#gmail.com',
3 => 'trainee',
4 => '9554512582',
5 => '6000',
6 => '23',
),
);
However that said, there is a lot going on in your example, as for reading the file in. If it's not to large the best bet would be to use file_get_contents() that will read the whole file in one go. Otherwise in this part
$handle = fopen($file,"r"); // Open the file and read
while($strBookData = fgets($handle, 4096)) { // To get Array from
$strDatas[] = $strBookData;
$strTableColumn = count($strBookData);
}
You would be better off just concatenating the text.
$strDatas = '';
$handle = fopen($file,"r"); // Open the file and read
while($strBookData = fgets($handle, 4096)) { // To get Array from
$strDatas .= $strBookData;
}
And then splitting like I did above.
I think that you should first explode using '\t' as delimiter to get the substrings separated by \t (Name|Code|Email|Designation|Number|Salary|Age)
and then explode each substring using '|' as delimiter.
I wish that can help you

PHP CSV string to array

I'm trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:
Delimiter: ,
Enclosure: "
New line: \r\n
Example content:
"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
When I try to parse it like this:
$url = "http://www.url-to-feed.com";
$csv = file_get_contents($url);
$data = str_getcsv($csv);
var_dump($data);
The last and first element are concatenated in one string:
[0]=> string(5) "12345"
...
[7]=> string(4) "0.04"
[8]=> string(19) "27-05-2013
"12346""
How can I fix this? Any help would be appreciated.
Do this:
$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
print_r($array);
It will give you an output like this:
Array
(
[0] => Array
(
[0] => 12345
[1] => Computers
[2] => Acer
[3] => 4
[4] => Varta
[5] => 5.93
[6] => 1
[7] => 0.04
[8] => 27-05-2013
)
[1] => Array
(
[0] => 12346
[1] => Computers
[2] => Acer
[3] => 5
[4] => Decra
[5] => 5.94
[6] => 1
[7] => 0.04
[8] => 27-05-2013
)
)
I hope this can be of some help.
You should use fgetcsv. Since you cannot import a file as a stream because the csv is a variable, then you should spoof the string as a file by using php://temp or php://memory first:
$fp = fopen("php://temp", 'r+');
fputs($fp, $csvText);
rewind($fp);
Then you will have no problem using fgetcsv:
$csv = [];
while ( ($data = fgetcsv($fp) ) !== FALSE ) {
$csv[] = $data;
}
fclose($fp)
$data will be an array of a single csv line (which may include line breaks or commas, etc), as it should be.
Caveat: The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes. (the default is 2 MB) http://www.php.net/manual/en/wrappers.php.php
Handy oneliner:
$csv = array_map('str_getcsv', file('data.csv'));
I have used following function to parse csv string to associative array
public function csvToArray($file) {
$rows = array();
$headers = array();
if (file_exists($file) && is_readable($file)) {
$handle = fopen($file, 'r');
while (!feof($handle)) {
$row = fgetcsv($handle, 10240, ',', '"');
if (empty($headers))
$headers = $row;
else if (is_array($row)) {
array_splice($row, count($headers));
$rows[] = array_combine($headers, $row);
}
}
fclose($handle);
} else {
throw new Exception($file . ' doesn`t exist or is not readable.');
}
return $rows;
}
if your csv file name is mycsv.csv then you call this function as:
$dataArray = csvToArray(mycsv.csv);
you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/
A modification of previous answers using array_map.
Blow up the CSV data with multiple lines.
$csv = array_map('str_getcsv', explode("\n", $csvData));
Slightly shorter version, without unnecessary second variable:
$csv = <<<'ENDLIST'
"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
ENDLIST;
$arr = explode("\n", $csv);
foreach ($arr as &$line) {
$line = str_getcsv($line);
}
If you need a name for the csv columns, you can use this method
$example= array_map(function($v) {$column = str_getcsv($v, ";");return array("foo" => $column[0],"bar" => $column[1]);},file('file.csv'));
If you have carriage return/line feeds within columns, str_getcsv will not work.
Try https://github.com/synappnz/php-csv
Use:
include "csv.php";
$csv = new csv(file_get_contents("filename.csv"));
$rows = $csv->rows();
foreach ($rows as $row)
{
// do something with $row
}
You can convert CSV string to Array with this function.
function csv2array(
$csv_string,
$delimiter = ",",
$skip_empty_lines = true,
$trim_fields = true,
$FirstLineTitle = false
) {
$arr = array_map(
function ( $line ) use ( &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ) {
if ($FirstLineTitle && !$FirstLine) {
$FirstLine = explode( $delimiter, $result[0] );
}
$lineResult = array_map(
function ( $field ) {
return str_replace( '!!Q!!', '"', utf8_decode( urldecode( $field ) ) );
},
$trim_fields ? array_map( 'trim', explode( $delimiter, $line ) ) : explode( $delimiter, $line )
);
return $FirstLineTitle ? array_combine( $FirstLine, $lineResult ) : $lineResult;
},
($result = preg_split(
$skip_empty_lines ? ( $trim_fields ? '/( *\R)+/s' : '/\R+/s' ) : '/\R/s',
preg_replace_callback(
'/"(.*?)"/s',
function ( $field ) {
return urlencode( utf8_encode( $field[1] ) );
},
$enc = preg_replace( '/(?<!")""/', '!!Q!!', $csv_string )
)
))
);
return $FirstLineTitle ? array_splice($arr, 1) : $arr;
}
Try this, it's working for me:
$delimiter = ",";
$enclosure = '"';
$escape = "\\" ;
$rows = array_filter(explode(PHP_EOL, $content));
$header = NULL;
$data = [];
foreach($rows as $row)
{
$row = str_getcsv ($row, $delimiter, $enclosure , $escape);
if(!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}

Categories