dora12345678 2017-05-20 18:14
浏览 37
已采纳

如何修剪在PHP中读取CSV文件的附件(“一些文本”)

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.

<?php
    // allows us to skip the first row while looping through the file 
     $i = 0;
    //web api
    $stocks = "https://www.google.com/finance/historical?output=csv&q=aapl";

    //read csv file
    $handle = fopen($stocks, 'r');
    //loop through CSV file
    while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {    
        if ($i > 0) { 
            trim($data[0]);
            trim($data[1]);
            trim($data[2]);
            trim($data[3]);
            trim($data[4]);
            trim($data[5]);

            // an array
            $chartArray[] = $data;
        }
        $i++;
    }

   fclose($handle);

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

?>

Screenshot

As you can see from the image, I am getting JSON with enclosure. ["19-May-17","153.38","153.98","152.63","153.06","26960788"].

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

  • 写回答

2条回答 默认 最新

  • douya2007 2017-05-20 18:34
    关注

    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;
        }
        $i++;
    }
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化