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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀