如何使用PHP将原始文本文件数据转换为json?

时间:2018-04-22 21:28:09

标签: php arrays json

我有一项任务是使用PHP和面向对象的主体将文本文件中的数据整理成JSON。 文本文件包含信息,显示如下(忽略#):

#product_num:name:cost
5:tv:59.99
7:radio:10.99

我创建了一个类,在这个类中,我有一个函数忽略数据中的任何#或空格,并将数据放入数组中并对其进行json_encode。当我回显这些数据时,它看起来像这样:

[{"1":"5:tv:59.99","2":"7:radio:10.99"}]

是否可以编写其他函数来进一步分离数据,例如它看起来更像:

[{"product_number":"5","name":"tv","cost":"59.99"},{"product_number":"7","name":"radio","cost":"10.99"}]

如果是这样,任何人都可以给我任何指示和提示,因为即使经过大量谷歌搜索,我也不知道在哪里或如何开始。

2 个答案:

答案 0 :(得分:0)

您的文件格式基本上是csv文件,PHP具有CSV导入功能。 http://php.net/manual/en/function.fgetcsv.php

如果向下滚动并查看CsvImporter示例,则可以复制/粘贴该示例并添加json_encode:

$!foo

答案 1 :(得分:0)

PHP中有一个函数用于读取值分隔行,如CSV;它被称为fgetcsv,它也可以通过SplFileObject::fgetcsv在面向对象的PHP中使用。

您需要读取每一行,添加变量标签,然后将其附加到数组。

根据文件的大小,您可能需要优化内存使用量,因为在您继续浏览文件时通过保存来增加阵列。

<?php
$file = new SplFileObject('test.txt', 'r'); //Load the file
$file->current(); //Skip the first line (Side note: seek(1) did not appear to work while testing)

$result = [];
do { //While there are lines in the file
    list($product_num, $name, $cost) = $file->fgetcsv(':'); //Break the line on the : delimiter into an array and populate the array into the three named values
    $result[] = [ //Build the new json representation and add to result array
        'product_num' => $product_num,
        'name' => $name,
        'cost' => $cost,
    ];
} while (!$file->eof());

file_put_contents('output.json', json_encode($result)); //Save the result