Manually build JSON encodable array in PHP - php

This is kind of a strange one. I have a CSV that I'm uploading and passing to a PHP script that parses it into arrays, encodes it into a JSON string and sends it back to be further processed by my Javascript. However, I am having difficulty getting the response in a format that is easily parsed. Maybe it can be parsed, I'm just not sure how to access the data within.
PHP script for handling and parsing the CSV:
<?php
$file = $_FILES['file'];
$tmp = $file['tmp_name'];
$row = 1;
$json = array();
if(($handle = fopen($tmp, 'r')) !== false){
while(($data = fgetcsv($handle, 10000, '\n')) !== false){
$num = count($data);
$row++;
for($i = 0; $i < $num; $i++){
$values = split(',', $data[$i]);
$value = array(
sName => $values[0],
sNick => $values[1],
sEmail => $values[2],
sSSOID => $values[3],
sPwd => $values[4],
sConfPwd => $values[5],
sDescr => $values[6]
);
array_push($json, $value);
}
print_r(json_encode($json));
}
fclose($handle);
}
?>
The output ends up being an iterative response where the first array contains the first row of the CSV and the second array contains the first and second rows (the third array contains the first, second, and third, etc. etc.). The very last array is the response that I want. It is a well-formed JSON string; I am just unsure of how to get only that response.
Sample response:
[{"sName":"John Doe","sNick":"John","sEmail":"jdoe#email.com","sSSOID":"jdoe","sPwd":"Admin1234","sConfPwd":"Admin1234","sDescr":"Likes cats"}][{"sName":"John Doe","sNick":"John","sEmail":"jdoe#email.com","sSSOID":"jdoe","sPwd":"Admin1234","sConfPwd":"Admin1234","sDescr":"Likes cats"},{"sName":"Bill Frank","sNick":"Bill","sEmail":"bfrank#email.com","sSSOID":"bfrank","sPwd":"Admin1234","sConfPwd":"Admin1234","sDescr":"Likes dogs"}][{"sName":"John Doe","sNick":"John","sEmail":"jdoe#email.com","sSSOID":"jdoe","sPwd":"Admin1234","sConfPwd":"Admin1234","sDescr":"Likes cats"},{"sName":"Bill Frank","sNick":"Bill","sEmail":"bfrank#gmail.com","sSSOID":"bfrank","sPwd":"Admin1234","sConfPwd":"Admin1234","sDescr":"Likes dogs"},{"sName":"Sam Smith","sNick":"Sam","sEmail":"ssmith#email.com","sSSOID":"ssmith","sPwd":"Admin1234","sConfPwd":"Admin1234","sDescr":"Likes music"}]
The only response I need is the final array:
[{"sName":"John Doe","sNick":"John","sEmail":"jdoe#email.com","sSSOID":"jdoe","sPwd":"Admin1234","sConfPwd":"Admin1234","sDescr":"Likes cats"},{"sName":"Bill Frank","sNick":"Bill","sEmail":"bfrank#email.com","sSSOID":"bfrank","sPwd":"Admin1234","sConfPwd":"Admin1234","sDescr":"Likes dogs"},{"sName":"Sam Smith","sNick":"Sam","sEmail":"ssmith#email.com","sSSOID":"ssmith","sPwd":"Admin1234","sConfPwd":"Admin1234","sDescr":"Likes music"}]

You might want to use
$json[] = $value;
instead of array_push and
echo json_encode($json);
instead of print_r. Also, move the print_r/echo call out of the while loop.

Move this line to after the fclose:
print_r(json_encode($json));

Try this:
$index = count($json) - 1;
echo json_encode($json[$index]);

Decode the JSON in your Javascript app, which will produce an array, then use .pop() to get the last value:
var json = json_decode('[{"sName" ......... ');
var lastelement = json.pop();

Related

Remap CSV as an array using first row as keys

Let's assume I have a CSV file, which looks like:
[Line 1]: ID, Name, Birthday, Phonenumber, Email
[Line 2]:
[Line 3]: 1, Jim, 1978-02-01, 555-23-256, jim.doe#donotreply.com
[Line 4]: 2, Mia, 1985-12-21, 555-23-876, mia#donotreply.com
[Line 5]: 3, Wil, 1962-05-07, 555-23-456, wil.doe#donotreply.com
Now I am trying to wrap my head around this question:
How can I parse this file with PHP to get the following array?
$people = array(
[1] = array(
[Name] => "Jim",
[Birthday] => "1978-02-01",
[Phonenumber] = "555-23-256",
[Email] => "jim.doe#donotreply.com",
),
...
);
Any idea?
Use fopen and fgetcsv
In order to do this you need to first write a function for retrieving the data from the CSV and storing it in a variable, the function below will do this using fopen.
First, you'll need a function to read the CSV:
function utf8_fopen_read($fileName) {
$fc = iconv('windows-1250', 'utf-8//IGNORE', file_get_contents($fileName));
$handle = fopen("php://memory", "rw");
fwrite($handle, $fc);
fseek($handle, 0);
return $handle;
}
Once you've done this you'll want to manipulate the data you've just retrieved so you can create a multi-dimensional array of the results, populating the data into the associative keys like you described in your question.
Now we are going to make a call to the function above and store the results in $data, using a while loop we are going to iterate through the entire CSV and store all of the information into $people row by row.
Populating your array:
$people = [];
if(($handle = utf8_fopen_read('path/to/csv.csv')) !== FALSE) {
while(($data = fgetcsv($handle, 0, ',')) !== FALSE) {
$people[$i] = [];
for($c = 0; $c < count($data); $c++) {
$info = $data[$c];
if($i == 0) $fields[$c] = str_replace(' ', '', $info);
if($i > 0) $people[$ii][$fields[$c]] = $info;
}
if($i > 0) $ii++;
$i++;
}
fclose($handle);
}

How to get multiple array JSON Data

I have Json Data with multiple array, and i try to get the data inside effect_property, but it keep return nothing.
Here is my code
$json = file_get_contents('data.json');
$json_data = json_decode($json,true);
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i][effect_property];
}
when i print the $path_data_action it show something like this:
{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
How can i get the source_path?
Probably the JSON you are decoding with :
$json_data = json_decode($json,true);
contains another JSON string at key effect_property. You could change that to JSON Object and it should work fine.
Otherwise, you could use json_decode again, like :
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i]effect_property];
$pathDataActionArr = json_decode($path_data_action , true);
$sourcePath = $pathDataActionArr['propTo']['sourcePath'];
}
Furthermore, to know any last occurred error with JSON encoding/decoding
json_last_error — Returns the last error occurred
UPDATE : I tried to decode the JSON you posted with code :
$fileContent = file_get_contents("/home/tarun/Desktop/test/abcd");
$jsonArray = json_decode($fileContent,true);
var_dump($jsonArray['t03_action']['data'][9]['effect_property']);
$effectPropertyArr = json_decode($jsonArray['t03_action']['data'][9]['effect_property'],true);
if(isset($effectPropertyArr['propTo']['source_path'])) {
var_dump($effectPropertyArr['propTo']['source_path']);
} else {
var_dump("No such key!");
}
Here, not all your elements of the array at key effect_property contains source_path. That's why :
if(isset($effectPropertyArr['propTo']['source_path'])) {
The above is working fine, with output :
/home/tarun/Desktop/test/temp.php:6:
string(205) "{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/18032022375907620062/","source_file":"1804100413270066.jpg","source_name":"Penguins.jpg"},"beforeAction":"0","action_order":"1"}"
/home/tarun/Desktop/test/temp.php:10:
string(32) "../uploads/18032022375907620062/"
// decoded array passed key of that array
$json_data['propTo']['source_path'];
try this ,Its working for me.
var data = {"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
alert(data.duration);
var Prop = data.propTo;
alert(Prop.source_path);`enter code here`

Reformat JSON array using PHP

I have a small PHP script that pulls in a CSV file and creates a JSON array from this.
However, I'd like to change the formatting of my outputted JSON array.
PHP:
<?php
$file = fopen('food.csv', 'r');
$allfile = [];
$idsColumnsWanted = array_flip([0, 1, 2]);
while (false !== $fields = fgetcsv($file)) {
$allfile[] = array_intersect_key($fields, $idsColumnsWanted);
}
fclose($file);
?>
Output:
var data = [["McDonalds","Fast Food","London"],["Marios","Italian","Manchester"]];
How do I transform my CSV into the following:
var data = [
{name:"McDonald's Fast Food",location:"London"},
{name:"Marios Italian",location:"Manchester"}
];
So it basically merges the first 2 items and adds name & location.
My food.csv file is:
McDonalds,Fast Food,London
Marios,Italian,Manchester
Next time please try something by yourself:
$data = [["McDonalds", "Fast Food", "London"], ["Marios", "Italian", "Manchester"]];
$newData = [];
foreach ($data as $info) {
$newData[] = [
'name' => $info[0] . " " . $info[1],
'location' => $info[2]
];
}
var_dump(json_encode($newData));
Output
string '[{"name":"McDonalds Fast Food","location":"London"},{"name":"Marios Italian","location":"Manchester"}]' (length=104)
You need to create a new array in the desired format, and simple json_encode it.
If you consider using jQuery - there it is
var data = [["McDonalds","Fast Food","London"],["Marios","Italian","Manchester"]];
var formated_data = {};
$.each(data, function(key, val) {
formated_data[key] = {name: val[0] + ' ' + val[1], location: val[2]}
});
console.log(formated_data);
Open CSV File then parse the CSV into an array.
Flow this Line,
<?php
$file="1_23.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json = json_encode($array);
print_r($json);
?>

Prevent array overwriting and instead create new array index

I have a file and I need the save the content of the file in my MySQL database. Here is the code that I am using to parse the file:
$lines = file($tmp_filename);
$data = array();
if (($handle = fopen($tmp_filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, ";", "\"", "\n")) !== FALSE)
{
$key = array_shift($row);
$data[$key] = $row;
}
fclose($handle);
}
and here are the contents of the file that I am parsing:
HDR;Payroll Interface;5496;2012-07-20
NM1;082;IN2;12345678;2001-01-15;Mr;Marcial;Gustav;Gustav,Marcial;PRI;Marcial
PR1;082;IN2;12345678;7 The School;Alvarez;Bahaghari; ;Gandum
PR2;082;IN2;12345678;400006;IND;M;M;2007-10-16;1976-03-31
PR3;082;IN2;12345678; ; ;A;
**truncated**
Click Here for full data
There are scenarios where the array has the same index and the same value but I still need to save these data but array overwriting occurs. What must be added to put the same array to a different array index?
Take a look at this and tell me what i am missing
The data in the array is being overwritten because you are reassigning the value of $key each time it is encountered.
What you want to do is create a secondary array as the $key value and push nodes into that array this way you end up with your expected result.
[
'NM1' => ['...', '...'],
'PR1' => ['...', '...']
]
The code would be,
while (($row = fgetcsv($handle, 1000, ";", "\"", "\n")) !== FALSE) {
$key = array_shift($row);
// Notice the extra []
$data[$key][] = $row;
}
Each key will now contain an array with a node for each row encountered.
try changing:
...
$data[$key] = $row;
to
...
$data[][$key] = $row;

PHP read in specific csv file column as an array

I am new to PHP and would like to be able to read in a csv file which has two columns, one is the number (kind of like a ID) then the other holds a integer value. I have looked up the fgetcsv function but I have not been able to find a way to read a specific column from the csv file.
I would like to get all the values from the second column only, without the heading.
Any way of doing this?
This is what I have so far:
$file = fopen('data.csv', 'r');
$line = fgetcsv($file);
And this is some sample data from the csv file:
ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00
Any help would be appreciated.
Thanks.
fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:
$data = array();
while($row = fgetcsv($file)) {
$data[] = $row;
}
The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:
$data[] = $row[1];
However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:
$data[$row[0]] = $row[1];
and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.
$csv = array_map("str_getcsv", file("data.csv", "r"));
$header = array_shift($csv);
// Seperate the header from data
$col = array_search("Value", $header);
foreach ($csv as $row) {
$array[] = $row[$col];
}
// Iterate through data set, creating array from Value column
$header = fgetcsv($h);
$rows = array();
while ($row = fgetcsv($h)) {
$rows []= array_combine($header, $row);
}
$fp = fopen($filePath, "r+");
$header = fgetcsv($fp);
while ($members = fgetcsv($fp)) {
$i = 0;
foreach ($members as $mem) {
$membersArray[ $i ][ ] = $mem;
$i++;
}
}
$newArray = array_combine($header, array_map("array_filter",$membersArray));
You can also use this class http://code.google.com/p/php-csv-parser/
<?php
require_once 'File/CSV/DataSource.php';
$csv = new File_CSV_DataSource;
$csv->load('data.csv');
var_export($csv->connect());
?>

Categories