在 PHP 中从 URL 获取 JSON 对象

使用 file_get_contents() 函数从 PHP 中的 URL 获取 JSON 对象

我们可以使用 file_get_contents()json_decode() 从 URL 中获取 JSON 对象。file_get_contents() 函数以字符串格式读取文件。我们应该在函数中指定文件的路径,或者我们甚至可以将函数中的 URL 作为第一个参数。我们应该启用 allow_url_fopen 以使用 file_get_contents() 函数。我们可以通过在 php.ini 文件中设置 phpini_set("allow_url_fopen", 1) 来启用它。json_decode() 函数将 JSON 对象转换为 PHP 对象。因此,我们可以将 JSON URL 中的对象作为 PHP 对象访问。

为了演示,我们将使用来自 jsonplaceholder 的虚拟 JSON URL。创建一个变量 $url 并将 URL 存储在其中。使用 URL https://jsonplaceholder.typicode.com/posts/1。URL 的 JSON 对象如下所示。接下来,创建一个 $json 变量并使用 $url 作为 file_get_contents() 函数的参数。现在,使用 json_decode() 函数将 JSON 字符串解码为 PHP 对象。将对象存储在 $jo 变量中。最后,使用 $jo 访问 title 对象并将其打印出来。

因此,我们从 Web 访问了一个包含 JSON 对象的 URL,并将其转换为 PHP。这样,我们就可以在 PHP 中从 URL 中获取 JSON 对象。

示例代码:

{
 "userId": 1,
 "id": 1,
 "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
 "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
<?php
$url = 'https://jsonplaceholder.typicode.com/posts/1';
$json = file_get_contents($url);
$jo = json_decode($json);
echo $jo->title;
?>

输出:

sunt aut facere repellat provident occaecati excepturi optio reprehenderit

[使用 curl 从 PHP 中的 URL 获取 JSON 对象]

curl 是一个命令行工具,用于发送和接收数据和文件。它使用支持的协议,如 HTTP、HTTPS、FTP 等,并从服务器或向服务器发送数据。在 PHP 中,有一个 curl 库可以让我们发出 HTTP 请求。我们可以使用 curl 从网络读取文件内容。PHP 中有各种 curl 函数可以方便我们发送和接收数据。我们可以使用它们从 URL 获取 JSON 对象。curl_init() 函数启动 curl。我们可以使用 curl_setopt() 函数来设置几个选项,例如返回传输和设置 URL。curl_exec() 函数执行操作,curl_close() 关闭 curl。

我们可以使用与第一种方法相同的 URL 来演示 curl 的用法。创建一个变量 $curl 并使用 curl_init() 函数启动 curl。使用 curl_setopt() 函数将 CURLOPT_RETURNTRANSFER 选项设置为 true。接下来,使用 CURLOPT_URL 选项设置 URL。使用 curl_exec() 函数和参数中的 $curl 执行 curl 并将其存储在 $res 变量中。使用 curl_close() 函数关闭 $curl 变量。接下来,使用 json_decode() 函数将 JSON 对象更改为 PHP 对象并显示 title 对象。

因此,我们可以使用 curl 从 URL 获取 JSON 对象。

示例代码:

<?php
 $curl= curl_init();
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($curl, CURLOPT_URL, 'https://jsonplaceholder.typicode.com/posts/1';
 $res = curl_exec($curl);
 curl_close($curl);
 $jo = json_decode($res);
 echo $jo->title; ?>

输出:

sunt aut facere repellat provident occaecati excepturi optio reprehenderit
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小柴没吃饱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值