john john john john -4 years ago 121
JSON Question

How to trim the enclosures (''some text") reading CSV file in PHP

I am trying to use a web API to get some data. The problem is that I need to convert CSV data to JSON format.

// allows us to skip the first row while looping through the file
$i = 0;
//web api
$stocks = "";

//read csv file
$handle = fopen($stocks, 'r');
//loop through CSV file
while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {
if ($i > 0) {

// an array
$chartArray[] = $data;


//Convert PHP Array to JSON String
print (json_encode($chartArray));



As you can see from the image, I am getting JSON with enclosure.

Please let me know if there is a solution. Thank you in advance!

Answer Source

You will never ever put non-string values into a json. Never.

Otherwise. You can simply convert the number parts to number, and the date parts to php date.

Something like this:

while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {    
    if ($i > 0) { 

        $data[0] = date('Y-m-d', strtotime($data[0]));
        $data[1] = intval($data[1]);
        $data[2] = intval($data[2]);
        $data[3] = intval($data[3]);
        $data[4] = intval($data[4]);
        $data[5] = intval($data[5]);

        $chartArray[] = $data;

But as soon as you convert it to a json, it will auto-place the " chars. So you will need to convert the strings at reciever (client?) side.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download