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条)

报告相同问题?

悬赏问题

  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信