【问题标题】:Converting a CSV to a specific json format and output a random row将 CSV 转换为特定的 json 格式并输出随机行
【发布时间】:2016-05-31 22:36:58
【问题描述】:

我曾经以文本格式存储数据,并使用 PHP 在文件中获取随机行并将其转换为 JSON。代码如下:

<?php
  // open the text file
  $Textfile   = file('file.txt', FILE_IGNORE_NEW_LINES);
  // get a random line
  $rand   = mt_rand(0, count($Textfile)-1);
  // set content title
  $title = "Same Title";
  // set a random content
  $content = $Textfile[$rand];
  // result
  $result = array('content'   => $content,
                  'title'     => $title);
  // set header
  header('Content-Type: application/json');
  // print the random quote
  echo json_encode($result);
?>

Json 输出为:

{"content":"some random content from a book","title":"Same Title"}

但我要添加更多书籍,所以我决定以 CSV 格式创建文件。 CSV 具有以下结构:

ID  | title              | content          |  page
1   | some unique title  | some content     |  25
2   | some other title   | some other cont  |  12

所以所需的输出将是:

{"ID":"1", "title":"some unique title", "content":"some content", "page", "25"}

我尝试使用我现有的 php 代码并简单地打开 csv 而不是文本文件:

<?php
  // read the csv file
  $file="newformat.csv";
  $csv= file_get_contents($file);
  // create the array
  $array = array_map("str_getcsv", explode("\n", $csv));
  $json = json_encode($array);

  // set header
  header('Content-Type: application/json');
  // print 
  echo json_encode($json);
?>

但这并没有提供与之前相同的输出,我不确定如何实现随机行。

有什么建议可以实现吗?

【问题讨论】:

    标签: php json csv


    【解决方案1】:

    这将获取 .csv 文件内容,将其拆分为行,获取随机行号,从 CSV 解析该行,并将值分配给所需的键,然后对其进行 JSON 编码。

    <?php
      const KEYS = ['ID', 'title', 'content', 'page'];
    
      $file = 'newformat.csv';
      $csv = file_get_contents($file);
      $lines = explode("\n", $csv);
      $num = count($lines);
    
      $randomLineNumber = rand(0, $num - 1); // get random line number
      $line = $lines[$randomLineNumber];     // get random line
      $array = array_combine(KEYS, str_getcsv($line)); // map values to keys
    
      header('content-type: application/json');
      echo json_encode($array);
    ?>
    

    【讨论】:

    • 感谢您的回复,上传到服务器后,我收到错误500。检查错误日志后,我注意到mod_fcgid: stderr: PHP Parse error: syntax error, unexpected '[' ... index.php on line 2
    • 您可能正在运行旧版本的 PHP。您可以尝试将此行:const KEYS = ['ID', 'title', 'content', 'page']; 替换为:$keys = array('ID', 'title', 'content', 'page'); 并将此行:$array = array_combine(KEYS, str_getcsv($line)); 替换为:$array = array_combine($keys, str_getcsv($line));
    • 问题是我有时会得到“假”。我尝试更改randomLineNumber (rand(1, $num);,但仍然在随机输出 json 时得到错误
    • 您的 CSV 文件是否有空行?
    • 您可以使用csvlint.io 来验证您的CSV 文件。在PHP_EOL 常量上使用explode 而不是"\n" 也可能是个好主意,所以explode(PHP_EOL, $csv)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2019-02-01
    • 2016-02-12
    • 2021-10-29
    • 1970-01-01
    • 2016-11-06
    相关资源
    最近更新 更多