在 PHP 中获取和读取数据

Olorunfemi Akinlua 2024年2月15日
  1. PHP 中的 GETPOST 方法
  2. 在 PHP 中使用 file_get_content()php://input 获取和读取用户输入
  3. 在 PHP 中使用 file_get_content()json_decode() 获取和读取请求
在 PHP 中获取和读取数据

我们在开发 PHP 应用程序时会遇到不同的内容。有时,我们需要读取文件并从用户、其他来源和应用程序获取内容。

在 PHP 和大多数编程语言中,我们可以使用不同的方式和过程来获取请求和读取内容。内置函数,如 file_get_content()json_decode() 允许我们获取内容解码 JSON 文件,以及诸如 php://input 之类的包装器从请求正文中读取原始数据.

本文将讨论我们可以用来在 PHP 中获取请求、用户输入和读取数据的函数。

PHP 中的 GETPOST 方法

为了获取数据,我们必须将其从一个来源转移到另一个来源;一个普遍的用例是从客户端到服务器,反之亦然。为此,我们需要两种流行的方法,GETPOST

GET 方法从指定资源请求数据,POST 方法将数据发送到服务器以创建或更新资源。但是,GET 方法中只允许使用 ASCII 字符。

抛开差异不谈,我们需要考虑 API(应用程序编程接口),它是连接不同应用程序的事实上的手段。大多数 API 以 JSON 格式提供它们的数据,供我们最终用户阅读或使用。

在 PHP 中使用 file_get_content()php://input 获取和读取用户输入

包装器 php://input 允许我们读取原始 POST 数据,并提供一种内存密集度较低的替代方法,无需 PHP 配置过程(特殊的 php.ini 指令)。此外,我们可以将 php://input 视为一个文件名,我们可以在 file_get_content() 过程的上下文中在我们的代码库中的任何位置使用它。

为了解释这个解释,让我们做一个简单的登录过程,它将使用 file_get_content() 和包装器 php://input 从表单中读取用户的数据。HTML 表单使用 POST 方法将用户数据发送到 api.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <form action="api.php" method="POST">
            <form method="POST">
                <label for="emai">Email address:</label><br>
                <input type="text" id="email" name="email"><br>
                <label for="password">Password:</label><br>
                <input type="text" id="password" name="password">
                <br><br>
                <button type="submit" name="btn_login" value="btn_login"> Login </button>
            </form>
    </div>
</body>

</html>

api.php 使用函数和包装器,并使用 var_dump() 函数显示信息。

<?php

$data2 = file_get_contents('php://input');
var_dump($data2);

?>

带有用户输入的 HTML 表单如下所示:

收集用户输入的登录页面

用户输入的 api.php 处理如下所示:

使用 PHP 输入处理数据

在 PHP 中使用 file_get_content()json_decode() 获取和读取请求

要读取 JSON 文件,我们可以使用内置函数 file_get_content() 读取 JSON 文件,然后使用函数 json_decode() 解码我们获得的字符串。

JSON(JavaScript Object Notation)是一种开放的标准文件格式,它将密钥对格式的数据存储为字符串。使用 json_decode() 函数,我们可以处理密钥对并创建 PHP 可以理解的关联数组或对象

除了 file_get_content() 函数中的字符串之外,还有另一个重要的参数,associative 参数。它可以设置为两个值:真或假;如果为真,则字符串将存储在关联数组中,如果为假,则将其存储为对象。

让我们阅读这个 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"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  },
  {
    "userId": 1,
    "id": 4,
    "title": "eum et est occaecati",
    "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
  },
  {
    "userId": 1,
    "id": 5,
    "title": "nesciunt quas odio",
    "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
  }
]

使用这个 PHP 代码,我们可以将 JSON 文件存储为关联数组并读取数组中的第一个数组元素。

<?php

$user_json = file_get_contents('user.json');

$users = json_decode($user_json, true);

print_r($users[0]);

我们还可以使用 foreach 循环来读取 JSON 文件中的所有标题。

<?php

$user_json = file_get_contents('user.json');

$users = json_decode($user_json, true);

foreach($users as $user) {
    print_r($user['title']);
    echo "\n";
}

代码片段的输出是:

sunt aut facere repellat provident occaecati excepturi optio reprehenderit
qui est esse
ea molestias quasi exercitationem repellat qui ipsa sit aut
eum et est occaecati
nesciunt quas odio

但是,如果我们想直接从 API 读取 JSON 数据,我们可以使用 cURL 库json_encode 函数。你可以查看此 GitHub 上的示例代码

Olorunfemi Akinlua avatar Olorunfemi Akinlua avatar

Olorunfemi is a lover of technology and computers. In addition, I write technology and coding content for developers and hobbyists. When not working, I learn to design, among other things.

LinkedIn

相关文章 - PHP JSON