0

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

2
  • 2
    why dont you convert it into json and read the data. you can use json_encode in php. Commented Sep 25, 2018 at 1:22
  • 1
    json_encode is your answer. Commented Sep 25, 2018 at 1:22

2 Answers 2

1

in server, echo json_encode($phpArray) and exit; in callback of ajax or init js variable, parse json to array with JSON.parse('jsonString');

1

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.