将CSV转换为特定的json格式并输出随机行

时间:2016-05-31 22:36:59

标签: php json csv

我曾经以文本格式存储数据,并使用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);
?>

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

有任何建议如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

这将获取.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);
?>