1

I'm looking at scraping data from a website, from a table, and display in a clean table in PHP.

Website example is below, you will notice the table of flight data. Any idea on how I can get PHP to loop over the data and place it into a table?

Data Example

0

2 Answers 2

5

Yes, i would recommend using Xpath

<h1>This is scraping flight radar:</h1>
   <?php
    $url = "https://www.flightradar24.com/data/flights/southwest-airlines-wn-swa";
    $html = file_get_contents($url);
    libxml_use_internal_errors(true);
    $doc = new \DOMDocument();
    if($doc->loadHTML($html))
    {
        $result = new \DOMDocument();
        $result->formatOutput = true;
        $table = $result->appendChild($result->createElement("table"));
        $thead = $table->appendChild($result->createElement("thead"));
        $tbody = $table->appendChild($result->createElement("tbody"));

        $xpath = new \DOMXPath($doc);

        $newRow = $thead->appendChild($result->createElement("tr"));

        foreach($xpath->query("//table[@id='tbl-datatable']/thead/tr/th[position()>1]") as $header)
        {
            $newRow->appendChild($result->createElement("th", trim($header->nodeValue)));
        }

        foreach($xpath->query("//table[@id='tbl-datatable']/tbody/tr") as $row)
        {
            $newRow = $tbody->appendChild($result->createElement("tr"));

            foreach($xpath->query("./td[position()>1 and position()<7]", $row) as $cell)
            {
                $newRow->appendChild($result->createElement("td", trim($cell->nodeValue)));
            }
        }

        echo $result->saveXML($result->documentElement);
    }
    ?>
1
  • This is really good. How would I pull back the URL's that sit behind the Flight No and the 'Live' links?
    – DARKOCEAN
    Commented Apr 26, 2016 at 21:24
1

As with any scraping endeavour, please keep in mind that you may be violating their terms of service, especially if you are re-publishing the content. That being said, https://github.com/FriendsOfPHP/Goutte is great for scraping tasks like this.

<?php
require 'vendor/autoload.php';
use Goutte\Client;

$data_url = 'https://www.flightradar24.com/data/flights/southwest-airlines-wn-swa';
$client = new Client();
$crawler = $client->request('GET', $data_url);
$crawler->filter('#tbl-datatable')->each(function ($node) {
    print $node->html()."\n";
});
1
  • The data is not being re-published. It's for personal use. Plus, we pay a large subscription cost to the website that allows access to take the data offline using various methods.
    – DARKOCEAN
    Commented Apr 26, 2016 at 20:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.