I'm trying to convert a JSON response to CSV file but I have a problem about arrays
Here is the conversion code to CSV
$jsonString = file_get_contents("feed.json");
$jsonDecoded = json_decode($jsonString, true);
$json = $jsonDecoded['results'];
jsonToCsv($json, "feed.csv");
function jsonToCsv ($json, $csvFilePath = false, $boolOutputFile = false) {
// See if the string contains something
if (empty($json)) {
die("The JSON string is empty!");
}
// If passed a string, turn it into an array
if (is_array($json) === false) {
$json = json_decode($json, true);
}
// If a path is included, open that file for handling. Otherwise, use a temp file (for echoing CSV string)
if ($csvFilePath !== false) {
$f = fopen($csvFilePath,'w+');
if ($f === false) {
die("Couldn't create the file to store the CSV, or the path is invalid. Make sure you're including the full path, INCLUDING the name of the output file (e.g. '../save/path/csvOutput.csv')");
}
}
else {
$boolEchoCsv = true;
if ($boolOutputFile === true) {
$boolEchoCsv = false;
}
$strTempFile = 'feed' . date("U") . ".csv";
$f = fopen($strTempFile,"w+");
}
$firstLineKeys = false;
foreach ($json as $line) {
if (empty($firstLineKeys)) {
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
// Using array_merge is important to maintain the order of keys acording to the first element
fputcsv($f, array_merge($firstLineKeys, $line));
}
fclose($f);
// Take the file and put it to a string/file for output (if no save path was included in function arguments)
if ($boolOutputFile === true) {
if ($csvFilePath !== false) {
$file = $csvFilePath;
}
else {
$file = $strTempFile;
}
// Output the file to the browser (for open/save)
if (file_exists($file)) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Length: ' . filesize($file));
readfile($file);
}
}
elseif ($boolEchoCsv === true) {
if (($handle = fopen($strTempFile, "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
echo implode(",",$data);
echo "<br />";
}
fclose($handle);
}
}
// Delete the temp file
unlink($strTempFile);
}
?>
And here is a example of feed.json content
{
"isError":false,
"messages":[
],
"results":[
{
"part_number_key":"DASDSA",
"buy_button_rank":1,
"category_id":11,
"id":123,
"brand":"brand",
"vendor_category_id":null,
"name":"Name",
"part_number":"part number",
"sale_price":12.31,
"currency":"RON",
"description":"description",
"url":"https://www.url.com",
"warranty":12,
"general_stock":10,
"weight":"0",
"status":1,
"recommended_price":12.19,
"images":[
{
"url":"https://url.com/images.jpg1",
"display_type":1
},
{
"url":"https://url.com/images.jpg2",
"display_type":0
},
{
"url":"https://url.com/images.jpg3",
"display_type":0
}
],
"characteristics":[
{
"id":8937,
"value":"value"
},
{
"id":8930,
"value":"value"
},
{
"id":8927,
"value":"value"
},
{
"id":8928,
"value":"value"
},
{
"id":5537,
"value":"value"
},
{
"id":8932,
"value":"value"
},
{
"id":8934,
"value":"value"
},
{
"id":8929,
"value":"value"
},
{
"id":7235,
"value":"value"
},
{
"id":6556,
"value":"value"
},
{
"id":5401,
"value":"value"
}
],
"attachments":[
],
"vat_id":1,
"family":{
"id":1104,
"name":"NAME",
"family_type_id":244
},
"start_date":[
],
"estimated_stock":10,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":{
"id":2484194,
"warranty_type":null,
"supply_lead_time":14
},
"offer_properties":[
],
"product_measurements":[
],
"availability":[
{
"warehouse_id":1,
"id":3
}
],
"stock":[
{
"warehouse_id":1,
"value":10
}
],
"handling_time":[
{
"warehouse_id":1,
"value":0
}
],
"barcode":[
],
"ean":[
],
"commission":{
"value":"20.0000",
"type":"percentage",
"id":"123",
"priority":"4",
"created":"2010-01-16 11:25:02"
},
"validation_status":[
{
"value":9,
"description":"Approved documentation",
"errors":null
}
],
"offer_validation_status":{
"value":1,
"description":"Saleable",
"errors":null
},
"ownership":1,
"best_offer_sale_price":11,
"best_offer_recommended_price":11,
"number_of_offers":1
},
{
"part_number_key":"D3129DKQW",
"buy_button_rank":1,
"category_id":456,
"id":123,
"brand":"Bluedio",
"vendor_category_id":null,
"name":"name",
"part_number":"part number",
"sale_price":123,
"currency":"EUR",
"description":"description",
"url":"https://url.com",
"warranty":24,
"general_stock":1,
"weight":"0",
"status":1,
"recommended_price":12,
"images":[
{
"url":"https://url.com/images.jpg1",
"display_type":1
},
{
"url":"https://url.com/images.jpg2",
"display_type":0
},
{
"url":"https://url.com/images.jpg3",
"display_type":0
}
],
"characteristics":[
{
"id":7774,
"value":"val"
},
{
"id":7947,
"value":"val"
},
{
"id":8001,
"value":"val"
},
{
"id":8937,
"value":"val"
},
{
"id":8930,
"value":"val"
},
{
"id":8927,
"value":"val"
},
{
"id":8928,
"value":"val"
},
{
"id":5537,
"value":"val"
},
{
"id":8932,
"value":"val"
},
{
"id":8934,
"value":"val"
},
{
"id":8929,
"value":"val"
},
{
"id":7235,
"value":"val"
},
{
"id":6556,
"value":"val"
},
{
"id":5401,
"value":"val"
}
],
"attachments":[
],
"vat_id":1,
"family":{
"id":123456,
"name":"Name",
"family_type_id":244
},
"start_date":[
],
"estimated_stock":144,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":{
"id":242414,
"warranty_type":null,
"supply_lead_time":14
},
"offer_properties":[
],
"product_measurements":[
],
"availability":[
{
"warehouse_id":1,
"id":3
}
],
"stock":[
{
"warehouse_id":1,
"value":9
}
],
"handling_time":[
{
"warehouse_id":1,
"value":0
}
],
"barcode":[
],
"ean":[
],
"commission":{
"value":"20.0000",
"type":"percentage",
"id":"12492",
"priority":"4",
"created":"2010-01-16 11:25:02"
},
"validation_status":[
{
"value":9,
"description":"Approved documentation",
"errors":null
}
],
"offer_validation_status":{
"value":1,
"description":"Saleable",
"errors":null
},
"ownership":1,
"best_offer_sale_price":77.31,
"best_offer_recommended_price":83.19,
"number_of_offers":1
}
]
}
Here is the output of the conversion
part_number_key,buy_button_rank,category_id,id,brand,vendor_category_id,name,part_number,sale_price,currency,description,url,warranty,general_stock,weight,status,recommended_price,images,characteristics,attachments,vat_id,family,start_date,estimated_stock,reversible_vat_charging,min_sale_price,max_sale_price,offer_details,offer_properties,product_measurements,availability,stock,handling_time,barcode,ean,commission,validation_status,offer_validation_status,ownership,best_offer_sale_price,best_offer_recommended_price,number_of_offers
DASDSA,1,11,123,brand,,Name,"part number",12.31,RON,description,https://www.url.com,12,10,0,1,12.19,Array,Array,Array,1,Array,Array,10,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,11,11,1
D3129DKQW,1,456,123,Bluedio,,name,"part number",123,EUR,description,https://url.com,24,1,0,1,12,Array,Array,Array,1,Array,Array,144,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,77.31,83.19,1
As you can see, there is array instead of values, can someone tell me why?
I tried reset() function but I get only the value from the first column ( part_number_key )
foreach ($json as $line){
if (empty($firstLineKeys)) {
$firstLineKeys = array_keys($line); print_r("aici3"); fputcsv($f,
$firstLineKeys); print_r("aici3"); $firstLineKeys = array_flip($firstLineKeys);
} fputcsv($f,
array_merge($firstLineKeys,
$line)); $first = reset($line); print_r($first);
}
I want to extract all columns but to show only the first row value from every from every column, for example at "images" column I would like to extract just the first url and same for the rest of columns
And one more thing, what is the best method to ignore few columns?
Thanks in advance!
Could anyone assist me with how I can pass one JSON object as a field to another without having quotes added? Basically I have a function that needs to be able to append a 'header' to a set of data pre parsed into JSON in some cases or just parse the data in others.
Problem is everything works fine until I try to pass a JSON object to be stored as a "payload" for a header, at which point the JSON becomes invalid because of the extra set of quotations attached.
The object that I am trying to use is:
{
"header": {
"table": "user",
"action": "insert",
"opType": "string",
"message": "Insert sucessful for user: 6",
"start of records": false,
"end of records": true
},
"data": "[
{
"id": "6",
"Surname": "Peter",
"Forename": "Kane",
"Email": "pkane#a.co.uk",
"Personal_Email": "p.kane#gmail.com",
"Home_Phone_No": "01216045429",
"Work_Phone_No": "087852489",
"Mobile_Phone_No": "77245455598",
"Address_Line_1": "1aplace",
"Address_Line_2": "thistown",
"Address_Line_3": "Someplace",
"Address_Line_4": "whereever",
"Post_Code": "W549AJ",
"Mode_ID": "44",
"Route_ID": "g12",
"image": ""
}
]"
}
The problem is the quotes after the "data" key and before the last curley brace without these everything validates fine.
As I've said Im using PHP Ive tried regex expressions substring etc but nothing seems to work.
my PHP is as follows:
public function dataToJSON($operationType, $table, $action, $data, $message, $header = true, $firstRecord = null) {
if ((!($operationType) === 'recordSet') and (!($operationType === 'error')) and (!($operationType === 'string') )) {
throw new Exception("Operation type:" . ' ' . $operationType . ' ' . 'passed to the dataToJSON function not recogonised');
}
if (!(is_null($firstRecord))) {
$isFirstRecord = $firstRecord;
$isLastRecord = !$firstRecord;
} else {
$isFirstRecord = false;
$isLastRecord = false;
}
if ($header) {
$jsonData = array('header' => array(
'table' => "$table",
'action' => "$action",
'opType' => "$operationType",
'message' => "$message",
'start of records' => $isFirstRecord,
'end of records' => $isLastRecord),
);
} else {
$jsonData = array();
}
$recordSet = array();
if ($operationType === 'recordSet') {
while ($row = mysql_fetch_assoc($data)) {
array_push($recordSet, $row);
}
if ($header) {
$jsonData ['data'] = $recordSet;
return json_encode($jsonData);
} else {
return json_encode($recordSet);
}
} else if (($operationType === 'error') || ($operationType === 'string')) {
if ($header) {
$jsonData ['data'] = $data;
return stripslashes(json_encode($jsonData));
} else {
return $data;
}
}
}
in order to use / parse json, it needs to be valid json... and those **"** chars make it invalid.
paste and process here to see what i mean: http://jsonformat.com/
A JSON object is nothing more than a mere string. To achieve what you are trying to achieve, you would probably need to decode and then re-encode your JSON string:
$jsonData['data'] = json_decode($data, TRUE);