Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建一个php表单并发出api请求_Php - Fatal编程技术网

创建一个php表单并发出api请求

创建一个php表单并发出api请求,php,Php,我必须创建一个简单的表单: <!DOCTYPE html> <html lang="en"> <head> <title>HTML page</title> </head> <body> <form method="post" action="process.php"> <input type="text" name="firstname" placeholder="rahul

我必须创建一个简单的表单:

 <!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML page</title>
</head>
<body>
<form method="post" action="process.php">
    <input type="text" name="firstname" placeholder="rahul_sharma">
    <button type="submit">send</button>
</form>
</body>
</html>
这将返回一个json响应

{"status":"Success","username":"your username is RAHULSHARMA"}
如果状态为成功,则必须显示用户名值

php新手。非常感谢您的帮助。

您可以使用调用API

在process.php文件中,可以使用$\u POST superglobal获取表单数据

$firstname = $_POST['firstname'];
之后,可以使用。运算符以形成url

$url = "https://your-api-site.com/api?" . $firstname;
接下来,您可以使用curl请求从url获取内容

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
获取url的结果将在$output变量中获得。假设API的结果是一个类似于您提供的JSON字符串,您可以使用JSON_decode PHP函数将其转换为关联数组

$result = json_decode($output);
现在,您可以使用if条件检查状态是否为Success并显示用户名

if ($result['status'] == "Success") {
  echo $result['username'];
}

研究不足。没有php编码尝试。太宽了。
$result = json_decode($output);
if ($result['status'] == "Success") {
  echo $result['username'];
}