Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch data (text) from an external website with PHP if possible?

I'm trying to extract data (text) from an external site and put it on my site. I want to get football scores of an external site and put it on mine. I've researched and found out I can do this using Preg_Match but i just can't seem to figure out how to extract data within html tags.

For example

this is the HTML structure of an external site.

<td valign="top" align="center" class="s1"><b>Text I Want To Fetch</b></td>

How would I fetch the text within tags? Would help me out allot! THANKS!

like image 453
user2651511 Avatar asked Oct 04 '22 08:10

user2651511


2 Answers

You can get the content of a webpage by using file_get_contents method.

Eg:

$content = file_get_contents('http://www.source.com/page.html');

like image 136
Duleendra Avatar answered Oct 09 '22 16:10

Duleendra


Try this:

<?php

$html = '<td valign="top" align="center" class="s1"><b>Text I Want To Fetch</b></td>';

$dom = new DOMDocument();
$dom->loadHTML($html);
$dom = $dom->getElementsByTagName('td'); //find td
$dom = $dom->item(0);                    //traverse the first td
$dom = $dom->getElementsByTagName('b');  //find b
$dom = $dom->item(0);                    //traverse the first b
$dom = $dom->textContent;                //get text

var_dump($dom);                          //dump it, echo, or print

Output

In this example, there weren't any other textContent, so if your HTML only has text within bold, you may use this as well:

<?php

$html = '<td valign="top" align="center" class="s1"><b>Text I Want To Fetch</b></td>';

$dom = new DOMDocument();
$dom->loadHTML($html);
$dom = $dom->textContent;

var_dump($dom);

Output

like image 26
Dave Chen Avatar answered Oct 09 '22 17:10

Dave Chen