title: CSV to JSON with PHP?
body: <p>I need to convert a <strong>CSV</strong> file to <strong>JSON</strong> on the server using PHP. I am using this script which works:</p>
  
  <pre><code>function csvToJSON($csv) {
      $rows = explode("\n", $csv);
  
      $i = 0;
      $len = count($rows);
      $json = "{\n" . '    "data" : [';
      foreach ($rows as $row) {
          $cols = explode(',', $row);
          $json .= "\n        {\n";
          $json .= '            "var0" : "' . $cols[0] . "\",\n";
          $json .= '            "var1" : "' . $cols[1] . "\",\n";
          $json .= '            "var2" : "' . $cols[2] . "\",\n";
          $json .= '            "var3" : "' . $cols[3] . "\",\n";
          $json .= '            "var4" : "' . $cols[4] . "\",\n";
          $json .= '            "var5" : "' . $cols[5] . "\",\n";
          $json .= '            "var6" : "' . $cols[6] . "\",\n";
          $json .= '            "var7" : "' . $cols[7] . "\",\n";
          $json .= '            "var8" : "' . $cols[8] . "\",\n";
          $json .= '            "var9" : "' . $cols[9] . "\",\n";
          $json .= '            "var10" : "' . $cols[10] . '"';
          $json .= "\n        }";
  
          if ($i !== $len - 1) {
              $json .= ',';
          }
  
          $i++;
      }
      $json .= "\n    ]\n}";
  
      return $json;
  }
  
  $json = csvToJSON($csv);
  $json = preg_replace('/[ \n]/', '', $json);
  
  header('Content-Type: text/plain');
  header('Cache-Control: no-cache');
  echo $json;
  </code></pre>
  
  <p>The <code>$csv</code> variable is a string resulting from a cURL request which returns the CSV content.</p>
  
  <p>I am sure this is not the most efficient PHP code to do it because I am a beginner developer and my knowledge of PHP is low. <strong>Is there a better, more efficient way to convert CSV to JSON using PHP?</strong></p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>Note.</strong> I am aware that I am adding whitespace and then removing it, I do this so I can have the option to return "readable" JSON by removing the line <code>$json = preg_replace('/[ \n]/', '', $json);</code> for testing purposes.</p>
  
  <p><strong>Edit.</strong> Thanks for your replies, based on them the new code is like this:</p>
  
  <pre><code>function csvToJson($csv) {
      $rows = explode("\n", trim($csv));
      $csvarr = array_map(function ($row) {
          $keys = array('var0','var1','var2','var3','var4','var5','var6','var7','var8','var9','var10');
          return array_combine($keys, str_getcsv($row));
      }, $rows);
      $json = json_encode($csvarr);
  
      return $json;
  }
  
  $json = csvToJson($csv);
  
  header('Content-Type: application/json');
  header('Cache-Control: no-cache');
  echo $json;
  </code></pre>