【问题标题】:I am trying to make plugin in wordpress, but php echo is not parsing html tags我正在尝试在 wordpress 中制作插件,但 php echo 没有解析 html 标签
【发布时间】:2020-06-29 05:07:32
【问题描述】:

我正在尝试在 wordpress 中制作一个插件,它需要制作一个包含 3 列的表格,该表格将从 api 中提取 json 记录并显示在表格中,但它显示所有 html 标签而不是制作一个 html表,请查看输出图像,告诉我我缺少什么。

<?php
function json_posts()
   {
     $response = wp_remote_get('API_FOR_JSON_DATA');
     if (is_array($response)) {
     $header = $response['headers']; 
     $body = $response['body']; 
     $array = json_decode( $body, true );

     echo '<table><thead><tr><th>Name</th><th>Email</th></tr></thead><tbody>';

     foreach ($array as $item) {
        echo "<tr><td>".$item['id']."</td><td>".$item['name']."</td><td>".$item['username']."</td></tr>";
     }

     echo '</tbody></table>';
   }

  }

 add_action('rest_api_init', function () {
 register_rest_route('myplugin/v1', 'posts', [
    'methods' => 'GET',
    'callback' => 'json_posts',
 ]);
});

Output Image

【问题讨论】:

  • 嗯?你在哪里输出这个?你用什么来测试这个?
  • 使用 apache 服务器,并尝试在 chrome __SITE__/wp-json/myplugin/v1/posts 中获取详细信息
  • 尝试返回值。我所有的 api 路由都带有 return 。我会在你的第一个回声之前 ob_start() 。并返回 ob_get_clean()
  • 你的 json_posts() 之后还有一个额外的 }
  • 哪里有多余的}3开{和3关

标签: php html json wordpress api


【解决方案1】:

试试

<?php
function json_posts()
{
    $response = wp_remote_get('API_FOR_JSON_DATA');
    if (is_array($response)) {
        $header = $response['headers'];
        $body = $response['body'];
        $array = json_decode( $body, true );

        ob_start();
        ?>
        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
            <?php
            foreach ($array as $item) {
                ?>
                <tr>
                    <td><?php echo $item['id']; ?></td>
                    <td><?php echo $item['name']; ?></td>
                    <td><?php echo $item['username']; ?></td>
                </tr>
                <?php
            }
            ?>
            </tbody>
        </table>
        <?php
        return ob_get_clean();
    }
}

add_action('rest_api_init', 'registerAPIExtensions');
function registerAPIExtensions(){
    register_rest_route('myplugin/v1', 'posts', [
        'methods' => WP_REST_Server::READABLE,
        'callback' => 'json_posts',
    ]);
}

【讨论】:

  • hmm.. 尝试邮递员postman.com 并显示您的结果。我想可能是你的浏览器。这是有道理的,因为没有 html doc
  • 您能通过anydesk (anydesk.com) 与我联系并自己查找。
  • @ShadabEqbal .. 嗯,当然。我有一个小时。我猜只是去 php 聊天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 2018-02-15
  • 1970-01-01
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
相关资源
最近更新 更多