在 php 中从 url 获取 json 对象
本文介绍如何在 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
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
如何在 php 中获取时间差的分钟数
发布时间:2023/03/29 浏览次数:204 分类:php
-
本文介绍了如何在 php 中获取时间差的分钟数,包括 date_diff()函数和数学公式。它包括 date_diff()函数和数学公式。
发布时间:2023/03/29 浏览次数:156 分类:php
-
本教程演示了如何将用户从页面重定向到 php 中的其他页面