I am trying to make plugin in wordpress, but php echo is not parsing html tags-ThrowExceptions

Exception or error:

I am trying to make a plugin in wordpress, it requires to make a table with 3 columns which will pull the json record from an api and display in the table, but it is showing all the html tags instead of making a html table, please look at the output image, tell me what i am missing.

<?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

How to solve:

Try

<?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',
    ]);
}

Leave a Reply

Your email address will not be published. Required fields are marked *