首页 > 解决方案 > 如何使 api 查询动态化

问题描述

php 新手,目前卡住了如何从我的 html 获取用户输入以传递给我的 api 查询?我不想将查询硬编码,而是希望将用户输入设置为 api 的查询

<?php
//keys

$CONSUMER_KEY = 'w';
$CONSUMER_SECRET = 'w';
$ACCESS_KEY = 'w';
$ACCESS_SECRET = 'w';

//include lib
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

//connect to the api
$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $ACCESS_KEY, $ACCESS_SECRET);
$content = $connection->get("account/verify_credentials");


// get tweets
// $tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=trump");
$tweets = $connection->get("search/tweets", ["q" => "trump"]);


?>

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Twitter Api Search</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
            <form action="" method="get">
                            <input name="keyword" type="text" placeholder="Search Tweets">

            </form>
            <?php foreach ($tweets->statuses as $key => $tweet) { ?>
            <img src="<?=$tweet->user->profile_image_url;?>" /><?=$tweet->text; ?><br>
        <?php } ?>
    </body>
</html>

标签: php

解决方案


我们需要做的事情:

  1. 将所有 API 代码放入一个文件中,命名为 api/twitter.php。
  2. 将所有 HTML 代码放入一个文件,称为 pages/twitter-search.php。
  3. 更改页面中的 HTML 表单以反映 API 文件路径。

api/twitter.php

//keys

$CONSUMER_KEY = 'w';
$CONSUMER_SECRET = 'w';
$ACCESS_KEY = 'w';
$ACCESS_SECRET = 'w';

//include lib
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

//connect to the api
$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $ACCESS_KEY, $ACCESS_SECRET);
$content = $connection->get("account/verify_credentials");


// get tweets
// $tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=trump");


// because in our form on our page we use a text input with the name 'keyword'
$tweets = $connection->get("search/tweets", ["q" => $_GET['keyword']]);


?>

页面/twitter.php

<?php
echo '<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Twitter Api Search</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
</head>
<body>
<form action="api/twitter.php" method="get">
    <input name="keyword" type="text" placeholder="Search Tweets">

</form>';

foreach ($tweets->statuses as $key => $tweet) {
    echo '<img src="'.$tweet->user->profile_image_url.'" />'.$tweet->text.'<br>';
}

echo '
</body>
</html>';
?>

请注意,在表单内部,我们的操作属性更改为“api/twitter.php”,这反映了您的 API 文件的新目的地。文本框输入的名称为“关键字”,这是 API 文件在运行时查找的名称。


推荐阅读