0

There's an external site http://example.com/phprender.php

Which returns the following html elements

<div id="phprender">
  <p id='101'>ABC</p>
  <p id='102'>Hello World!</p>
</div>

How do I retrieve the data "ABC" so I can use that data to display in my own site?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
joke4me
  • 35
  • 1
  • 1
  • 5
  • 3
    Use `file_get_contents` to download the HTML, and `DOMDocument` to parse it. – Barmar Feb 20 '15 at 11:39
  • if its legal to scrape contents from that particular site, then you should look into HTML Parsers in PHP, DOMDocument in particular – Kevin Feb 20 '15 at 11:40

4 Answers4

1

Using DomDocument to parse HTML, and DOMXpath to retrieve:

    $url="http://example.com/phprender.php";
    $doc = new DOMDocument();
    $content=file_get_contents($url);
    $doc->loadHTML($content);
    $xpath = new DOMXpath($doc);

    $elements=$xpath->query("//p[@id='101']");
    if (!is_null($elements))
    foreach ($elements as $ele) {
         echo $ele->nodeValue;
    }
Adam
  • 17,838
  • 32
  • 54
0

file_get_contents

<?php
$html = file_get_contents('http://example.com/phprender.php');
echo $html;
?>


For client way
Is there a JavaScript way to do file_get_contents()?

Community
  • 1
  • 1
Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47
0

if you want to use javascript approach, make sure the external site have cors disabled. You can read here. Then use jquery to load it:

$("#content").load("services.html #IdOfelementToLoad");

you can use #101 in your case.

  • I don't have access to the external site. – joke4me Feb 20 '15 at 12:36
  • then you may want to use php approach instead. Try http://davidwalsh.name/curl-download then substr $returned_content to get only what you need. –  Feb 20 '15 at 13:11
0

PHP Solution

You can use file_get_contents and perform a regular expression match like this:

preg_match('/<p.*>(.*)<\/p>/i',file_get_contents('http://example.com/phprender.php'), $matches);
print_r($matches[1]);

JQuery Solution

With JQuery you can use get for retrieve remote html like this:

$.get( "http://example.com/phprender.php", function( data ) {
  $( ".result" ).html( data );
  var myMatch = data.match(/<p.*>(.*)<\/p>/i);
});

or using DOM instead match.

Marco
  • 1
  • 2