donglie1898 2015-03-12 06:25
浏览 197
已采纳

从php远程csv获取json数组

For one of my php code, i want the json array as following from remote csv file in php.

The remote csv file: www.xyz.com/dir/records.csv

NAME    Age ID
Jhon    45  101
Bhil    42  102
Tone    41  103

I want a function which converts this CSV file to a JSON array

Something Like this:

$json = '{"records": 
       [
         {"Name":"Jhon", "Age":"45", "id":"101"},
         {"Name":"Bhil", "Age":"42", "id":"102"},
         {"Name":"Tone", "Age":"41", "id":"103"},
       ]
    }';

Kindly guide me, how to incopporate the above csv file to get the above json array for the follwoing php code.

$myjson = json_decode($json, true);  
  foreach ( $myjson['records'] as $row ) {  
                        if ($row['id'] =='101') { 
                          foreach ( $row as $field => $value ) {  
                               // do the work here
                             }
                   }
         }
  • 写回答

3条回答 默认 最新

  • dongwen2896 2015-03-12 06:54
    关注

    Here is the solution, You can modify your output array format accordingly inside csvToJson() function

    <?php
    
         function csvToJson($filename) {
                $handle = fopen($filename,"r");
                $i=0;
                if($handle) {
                    while(($line = fgetcsv($handle,1000,",","'")) !== FALSE)
                    {
                        if($i == 0) {
                            $c = 0;
                            foreach($line as $col) {
                                $cols[$c] = $col;
                                $c++;
                            }
                        } else if($i > 0) {
                            $c = 0;
                            foreach($line as $col) {
                                $data[$i][$cols[$c]] = $col;
                                $c++;
                            }
                        }
                        $i++;
                    }
                }
                $data2['records'] = array($data);       
                fclose($handle);
                // return json_encode($data2);  /*you don't have to convert it into json if you want to use it in your php foreach loop you can directly return this*/ 
                return json_encode($data2);
            }
    
            $json = csvToJson('records.csv');
            echo "<pre>";
            print_r($json);
    
        ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥500 高有偿提问!求优化设计微信小程序
  • ¥15 matlab在安装时报错 无法找到入口 无法定位程序输入点
  • ¥15 收益高的广告联盟有哪些
  • ¥15 Android Studio webview 的使用问题, 播放器横屏全屏
  • ¥15 删掉jdk后重新下载,Java web所需要的eclipse无法使用
  • ¥15 uniapp正式环境中通过webapi将本地数据推送到设备出现的跨域问题
  • ¥15 xui建立节点,显示错误
  • ¥15 关于#单片机#的问题:开始、复位、十进制的功能可以实现,但是切换八进制的功能无法实现(按下按键也没有效果),把初始状态调成八进制,也是八进制可以实现但是切换到十进制不行(相关搜索:汇编语言|计数器)
  • ¥15 VINS-Mono或Fusion中feature_manager中estimated_depth是特征的深度还是逆深度?
  • ¥15 谷歌浏览器如何备份抖音网页数据