Reputation: 71
Hey just a small thing I am stuck on.
I do have the structure ready for the JS array but I need to assign it to a variable like
var data ={ Php array }
Here is the structure of my php array: https://imgur.com/a/LPbCqEu
This is just a part of the array.
My code looks like this:
$csvfile = 'Property_CSVTruncated.csv';
$handle = fopen($csvfile, 'r');
$jsData = array(
'properties' =>array()
);
$header = NULL;
while (($row = fgetcsv($handle, 1000000, ',')) !== FALSE) {
$i = 0;
if (!$header) {
$header = $row;
} else {
$data = array_combine($header, $row);
$fields = array(
'_id' => $data['C4021040'],
'index' => $i,
'price' => $data['123'],
'picture' => "https://ihatetomatoes.net/demos/_rw/01-real-estate/tn_property01.jpg",
'city' => "Calgary",
'MLS# ' => $data['C4021040'],
'address' => $data['6 ASPEN RIDGE LN SW'],
'latitude' => $data['51.045681'],
'longitude' => $data['-114.191544'],
'Bed' => $data['123'],
'Bath' => $data['123'],
'capSpaces' => $data['T3H 5H9'],
);
array_push($jsData['properties'], $fields);
}
$i++;
}
fclose($handle);
$str = "const data = ";
print($str);
header('Content-type: application/json');
json_encode($jsData, JSON_NUMERIC_CHECK);
$jsonFile = fopen('csvTojs.js', 'w');
fwrite($jsonFile, json_encode($jsData));
fclose($jsonFile);
So basically I need that string 'var data = ' and then prints the array.
Anyway to do that in php itself?
Thanks
Upvotes: 0
Views: 51
Reputation: 2724
Use json_encode()
<script>
var data = <?php echo json_encode($jsData, JSON_PRETTY_PRINT); ?>
</script>
Or in your case:
header('Content-Type: application/json');
echo json_encode($jsData);
exit;
Upvotes: 1
Reputation: 61
in server, echo json_encode($phpArray) and exit; in callback of ajax or init js variable, parse json to array with JSON.parse('jsonString');
Upvotes: 1