13

I've read through quite a few questions on here and I'm not sure if I should be using file_get_contents or file_get_html for this.

All that I'm trying to do is use PHP to display the two tables from this page on my website: http://www.statmyweb.com/recently-analyzed/

I know how to get their full page and display it on my site of course, but I can't figure out how I'm able to just pull those two tables without also getting the header/footer.

keyser
  • 18,829
  • 16
  • 59
  • 101

3 Answers3

33

You want file_get_html because file_get_contents will load the response body into a string but file_get_html will load it into simple-html-dom.

$dom = file_get_html($url);
$tables = $dom->find('table');
echo $tables[0];
echo $tables[1];

Alternatively you could use file_get_contents along with str_get_html:

$dom = str_get_html(file_get_contents($url));

But that would be silly.

pguardiario
  • 53,827
  • 19
  • 119
  • 159
  • how can you cover $dom in string,which have similar string which we can get by file_get_content or do we any other function like file_get_content to get string from $dom – Nitin Jun 30 '16 at 10:14
  • 2
    Normally, it would be silly. Except perhaps you can't use either file_get_contents or file_get_html because of limitations (eg allow_url_fopen is off) In which case you are going to probably collect the string with curl and then use str_get_html. Not really the OPs question but it might help someone .... – niccol May 16 '19 at 22:03
5

You are not able to specify in file_get_contents() just to retrieve the tables.

You would have to get the return value of file_get_contents() using:

$result = file_get_contents("urlHere");

And then analyse the $result variable and extract what information you need to output.

EM-Creations
  • 4,195
  • 4
  • 40
  • 56
0

Take the full website content by file_get_contents(), then apply preg_match on the content you have got with <table> and </table>. This will bring you all the contents under the table tags. While showing it in your web page, just put a <table> then echo your matched content and a </table> at the end.

programmer
  • 167
  • 1
  • 10
  • +1 This would be painful (especially when a tool like simple_html_dom is available), but would definitely work. – rodrigo-silveira Jul 25 '13 at 14:54
  • It will work for this specific example, but it will fail on certain other cases, like when there is a nested ```table``` element inside a ```table``` – Yuval A. Jun 29 '15 at 12:47
  • 1
    As previously mentioned, regex functions represent a suboptimal tool for the task. – mickmackusa Jul 24 '18 at 05:00