编程爱好者

 找回密码
 立即注册

微信扫码 , 快速开始

QQ登录

只需一步,快速开始

搜索
查看: 12025|回复: 0

php读取json文件

[复制链接]
  • TA的每日心情
    奋斗
    2024-12-2 00:06
  • 签到天数: 4 天

    [LV.2]偶尔看看I

    14

    主题

    1

    回帖

    1950

    积分

    管理员

    积分
    1950
    发表于 2024-5-19 17:42:28 | 显示全部楼层 |阅读模式
    以下是几种PHP读取JSON文件的实现方法:

    方法一:使用file_get_contents()和json_decode()函数。

    $jsonString = file_get_contents('path/to/file.json');
    $data = json_decode($jsonString, true);

    // 注意,第二个参数为true,将返回一个数组,而不是一个对象

    方法二:使用file_get_contents()和json_decode()函数,但在读取文件之前加上错误处理。

    $file = 'path/to/file.json';
    if (file_exists($file)) {
        $jsonString = file_get_contents($file);
        $data = json_decode($jsonString, true);
    } else {
        die("File does not exist.");
    }

    方法三:使用fopen()和fread()函数。

    $file = fopen('path/to/file.json', 'r');
    $jsonString = fread($file, filesize('path/to/file.json'));
    fclose($file);
    $data = json_decode($jsonString, true);

    方法四:使用cURL库从URL中读取JSON数据。

    $url = 'http://example.com/data.json';
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $jsonString = curl_exec($curl);
    curl_close($curl);
    $data = json_decode($jsonString, true);

    方法五:使用file_get_contents()和stream_context_create()函数。

    $options = array(
        'http' => array(
            'method' => 'GET',
            'header' => 'Content-type: application/x-www-form-urlencoded\r\n'
        )
    );
    $context = stream_context_create($options);
    $jsonString = file_get_contents('path/to/file.json', false, $context);
    $data = json_decode($jsonString, true);

    以上是几种常用的PHP读取JSON文件的方法,根据具体需求和环境,可以选择适合的方法。

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    Archiver|手机版|编程爱好者 ( 渝ICP备2022000184号-3 )

    GMT+8, 2025-7-13 04:33 , Processed in 0.082124 second(s), 21 queries .

    Powered by Discuz! X3.5

    Copyright © 2001-2024 Tencent Cloud.

    快速回复 返回顶部 返回列表