簡體   English   中英

php json 解碼一個txt文件

[英]php json decode a txt file

我有以下文件:

數據.txt

{name:yekky}{name:mussie}{name:jessecasicas}

我是 PHP 的新手。 你知道我如何使用 PHP 對上面的 JSON 進行解碼嗎?

我的 PHP 代碼

var_dump(json_decode('data.txt', true));// var_dump value null

foreach ($data->name as $result) {
        echo $result.'<br />';
    }

json_decode將字符串作為參數。 使用file_get_contents讀入文件

$json_data = file_get_contents('data.txt');
json_decode($json_data, true);

您確實需要通過在字符串周圍添加引號、對象之間的逗號並將對象放置在包含數組(或對象)中來將示例字符串調整為有效的 JSON。

[{"name":"yekky"}, {"name":"mussie"}, {"name":"jessecasicas"}]

正如我在您的其他問題中提到的,您沒有生產有效的 JSON。 在那里查看我的答案,了解如何創建它。 這將導致類似的事情

[{"name":"yekky"},{"name":"mussie"},{"name":"jessecasicas"}]

(我不知道,你的引號在哪里,但json_encode()通常會產生有效的 json)

這很容易閱讀

$data = json_decode(file_get_contents('data.txt'), true);

您的 JSON 數據無效。 您在那里有多個對象(並且您缺少引號),您需要一些方法將它們分開,然后再將它們提供給json_decode

$data = json_decode(file_get_contents('data.txt'), true);

但是您的 JSON 需要正確格式化:

[ {"name":"yekky"}, ... ]

根據JSONLint ,這不是一個有效的 JSON 文件。 如果是,您必須先閱讀它:

$jsonBytes = file_get_contents('data.json');
$data = json_decode($jsonBytes, true);
/* Do something with data.
If you set the second argument of json_decode (as above), it's an array,
otherwise an object.
*/

你必須閱讀文件!

$json = file_get_contents('data.txt');
var_dump(json_decode($json, true));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM