How to consume and display external data in WordPress from another website

I am trying to access data from another website to display on a WordPress Website I am developing. So far I have the following:

<?php
    /*
       Template Name: Testing remote data
    */

get_header(); 

<div class="main">
    <div class="col-sm-12">
      <header>
          <h2>Testing remote data</h2>
      </header>
    </div>
    <div class="container">
        <div id="content" role="main">
            <div class="col-sm-12">
                <?php
                    $url="http://www.bbc.co.uk/news/";// this url is only for example purposes
                    $request = wp_remote_get( $url );

                    if(is_wp_error($request)) {
                        return false;
                    } else {
                        $body = $request['body'];
                    }

                    echo $body;

            </div>
         </div>
     </div>
 </div>

This works fine. However, I get the whole body content. How would I go about getting specific sections of the body? If any one could help me with this I would really appreciate it. Sorry if it’s an obvious one but I am new to WordPress and I am still far from comfortable with it.

2 Answers
2

// make request... (optionally save in transient for faster future fetches)
$dom = new DOMDocument();
$dom->loadHTML(wp_remote_retrieve_body($request));
$sections=$dom->getElementsByTagName("section");
foreach ($sections as $section) {
    // Do something...
    }

Leave a Comment