繁体   English   中英

如何使用 PHP 在新页面中打开 API 列表中的项目

[英]How to open an item from an API list in a new page with PHP

我有一个在 API 中查找并在表格中显示结果的代码。 如下。

<?php
$apikey = "api_key=my_api_key";
$url = "http://api.link.com/property?" . implode("&", array($apikey));

$result = json_decode(file_get_contents($url, TRUE));
<table>
<thead>
    <tr>
        <th>ID</th>
        <th>Type</th>
        <th>Name</th>
        <th>Title</th>
    </tr>
</thead>
<tbody>
<?php
foreach ($result->properties as $row) { 
?>
    <tr>
        <td><?php echo $row->id;?></td>
        <td><?php echo $row->type;?></td>
        <td><?php echo $row->name;?></td>
        <td><a href="api-item.php?id=<?php echo $row->id; ?>"><?php echo $row->title; ?></a></td>
</tr>
<?php } ?>
    </tbody>
</table>

我需要在新页面中打开每个项目,其中显示每个唯一 ID 的所有选项。

 <?php //api-item.php $post_id = $_GET['id']; $apikey = "api_key=my_api&id=".$post_id; $url = "http://api.link.com/property?" . implode("&", array($apikey)); $result = json_decode(file_get_contents($url, TRUE)); foreach ($result->properties as $row) { ?> <strong><?php echo $row->title; ?></strong><br><br> <strong>DESCRIPTION</strong><br> <?php echo $row->description; ?> <strong>CONSIDERATIONS</strong><br> <?php echo $row->considerations; ?> <?php } ?>

谢谢大家! 问题解决了!

(用户已使用代码部分编辑了他的问题,以链接此答案中存在的 $row->action td)。

我猜您正在使用项目 ID 来标识每个页面,因此您可以尝试以下代码:

<tr>
    <td><a href="theItemPage.php?id=<?php echo $row->id;?>" target="_blank"><?php echo $row->id;?></a></td>
    <td><?php echo $row->type;?></td>
    <td><?php echo $row->name;?></td>
    <td><?php echo $row->action;?></td>
</tr>

当然,您可以将标签移动到您需要的任何位置(例如,如果您希望用户单击名称)。

鉴于您的编辑,这是您应该使用的稍微重构的代码:

<?php //api-item.php
    $post_id = $_GET['id'];
    $apikey = "api_key=my_api&id=".$post_id;
    $url = "http://api.link.com/property?" . implode("&", array($apikey));

    $result = json_decode(file_get_contents($url, TRUE));

    // You don't need to re-assign $post_id, you already did it on the top of the page.
    $output = "";
    foreach ($result->properties as $row) {

        $output .= "<strong>".$row->title."</strong><br><br>";
        $output .= "<strong>DESCRIPTION</strong><br>".$row->description."<br><br>";
        $output .= "<strong>CONSIDERATIONS</strong><br>$row->considerations;
    }
    echo $output;
  1. 您不需要在 for 循环中重新声明 $post_id,作为参数传递的 ID 值是每页命中一个。
  2. 将 $post_id 连接到页面顶部的 api 字符串时要小心,检查重构的代码。

暂无
暂无

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

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