简体   繁体   English

无法使用PHP访问API密钥…知道怎么了吗?

[英]Unable to Access API Key with PHP…any idea what's up?

I am a junior programmer. 我是一名初级程序员。 Recently I've been trying to develop in PHP. 最近,我一直在尝试用PHP开发。 I am trying to create a basic page about countries. 我正在尝试创建有关国家的基本页面。 For some reason I cannot grab the information from this API page. 由于某些原因,我无法从此API页面获取信息。 Can anyone give me some tips? 谁能给我一些提示?

Here is what a sample country array looks like. 这是样本国家/地区数组的样子。 Ideally I would like to try to grab the "name" attribute. 理想情况下,我想尝试获取“名称”属性。

在此处输入图片说明

Here is my HTML and PHP: 这是我的HTML和PHP:

<?php

if(!empty($_GET['country'])) {
$country_url = 'https://restcountries.eu/rest/v1/name/' . urlencode($_GET['country']) . '?fullText=true';
$country_json = file_get_contents($country_url);
$country_array = json_decode($country_url, true);
           }

?>

 <!DOCTYPE html>
     <html lang="en">
        <head>
            <meta charset = "utf-8" />
            <title> PHP Country Practice </title>
        </head>
     <body>
        <form action="">
            <input type = "text" name = "country" />
            <button type="submit">submit </button>
        </form>

<?php

if(!empty($country_array)) {
    echo '<p> $country_array['name'] </p>';
    }
    ?>
</body>
</html>

您将返回一个关联数组,因此请使用如下标识符:

$country_array[0]['name']

If it is object use the below code. 如果是对象,请使用以下代码。

    echo $country_array[0]->name;

For array use 供阵列使用

    echo $country_array[0]['name'];
  1. You need to access the correct array index , in this case 0 . 您需要访问正确的数组index ,在本例中为0
  2. Variables don't expand inside single-quotes , you need to use double-quotes and surround it with brackets {} (tks AbraCadaver ), ie: 变量不会单引号扩展 ,您需要使用双引号并将其括在方括号{} (tks AbraCadaver ),即:

echo "<p> {$country_array[0]['name']} </p>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM