【发布时间】: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);
?>
但这并没有提供与之前相同的输出,我不确定如何实现随机行。
有什么建议可以实现吗?
【问题讨论】: