【问题标题】:How to parse JSON into CSV in PHP for Social Mention API如何在 PHP 中将 JSON 解析为 CSV for Social Mention API
【发布时间】:2013-03-20 04:30:13
【问题描述】:

我需要在 SocialMention.com 上查询“Colorado Springs”和“District 11”,然后将数据拉回 CSV 文件中。我是一名老程序员,但对 PHP 和 JSON 很陌生。这是简单的php代码:

<?php 
$curl = curl_init('http://api.socialmention.com/search?q=%22colorado+springs%22+%22district+11%22&f=json&src[]=twitter&sentiment=true&meta=info');
$result = curl_exec($curl); 
echo $result; 
?> 

如何解析 $result 并将其存储在 CSV 文件中?我已经对此进行了 6 天的研究,并尝试了我能找到的所有示例,但都没有运气。在下面的示例中,我不断收到“foreach 中的参数无效”错误。

【问题讨论】:

    标签: php json url


    【解决方案1】:

    您的问题很广泛,因为您并没有真正说出您想如何解析$result,但您甚至没有得到$result,因为curl_exec 实际上会打印出它的内容。相反,您可以设置curl_setopt($curl, CURLOPT_RETURNTRANSFER, true),或者您可能只使用$result = file_get_contents($url);

    无论如何,您可以通过$data = json_decode($result, true) 将结果从 JSON 更改为可用的 PHP 数据结构。第二个参数强制关联数组,这可能更适合您的目的。

    然后就可以写入CSV文件了:

    $fh = fopen('csvfile', 'w');
    foreach ($result['items'] as $items) {
        fputcsv($fh, $items);
    }
    

    【讨论】:

      【解决方案2】:

      你也可以参考这两个链接

      1.Parsing JSON file with PHP

      2.php writing to csv from an array

      $json_a=json_decode($string,true); //decodes json
      
      //writes to csv
       $fp = fopen('file.csv', 'w');
      
          for ($i = 0; $i < count($json_a); $i++) {
              $fields = //json object feids here
              fputcsv($fp, $fields);
          }
      
          fclose($fp);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 2022-12-13
        相关资源
        最近更新 更多