1

How can I use PHP to grab some html from a different (local) page?

I have a page "Product1.htm" and I want the text from the div with the class"price" to be found and then displayed on a different page: "Products_overview.htm". So inside Products_overview.htm is something, PHP i guess, which targets product1.htm and displays the contents of "Price" DIV.

No idea how to do this though I'm sure it must be embarrassingly simple! Any help?

  • You may want to checkout this SO thread if you're willing to use JavaScript instead of PHP http://stackoverflow.com/questions/405409/use-jquery-selectors-on-ajax-loaded-html – Björn Kaiser Jan 21 '12 at 12:38

4 Answers4

1

Strictly speaking, it is probably best to figure out how the content for the div "price" is being generated, then just reproduce that in Products_overview.htm. If there is no way to do this, then you can use CURL:

Assuming PHP needs to parse the .htm file before the div is outputted:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://localhost/path/to/Product1.htm"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$content = curl_exec($ch); 
if(preg_match('/<div class=\'Price\'>(.*?)<\/div>/is', $content, $matches) { 
    echo $matches[1]; 
}
cegfault
  • 6,442
  • 3
  • 27
  • 49
  • The content of the div"price" is entered by hand, by me! The idea is for any change here to be reflected on other pages which display a price. cURL looked promising but I was attracted by the simplicity of the Simple HTML DOM Solution. I'm gonna look into cURL further thou! Thanks – Simon Coombes Jan 21 '12 at 14:05
1

Simple way: use simple HTML Dom:

Example:

Page.html

Some html...

<div class="price">
Vivamus malesuada hendrerit metus, eu viverra odio viverra nec. Maecenas nec felis est, sit amet molestie massa. Morbi odio dolor, scelerisque eget bibendum et, volutpat non risus. Curabitur eleifend, lacus non rutrum sollicitudin, est diam fermentum nisl, vel lacinia felis felis quis odio. Aliquam mollis, est nec porttitor feugiat, velit risus dapibus dolor, ac viverra tortor
</div>

Some html...

PHP File:

<?php
include 'simple_html_dom.php';
$html = file_get_html('page.html');

echo $html->find("div[class=price]", 0); // will echo content inside a <div class="price"> </div>
?>
Zul
  • 3,627
  • 3
  • 21
  • 35
0

You can use either file_get_contents( 'http://..../Product1.html') or cURL and than parse it as normal text.

Vyktor
  • 20,559
  • 6
  • 64
  • 96
0

Use cURL (as per @cegfault's answer). However, to get the text itself, use a HTML parser like DOMDocument.

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://localhost/path/to/Product1.htm"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$content = curl_exec($ch); 
$doc = new DOMDocument();
$doc->loadHTML($content);
$finder = new DomXPath($doc);
$classname="price";
$nodes = $finder->query("//div[contains(@class, '$classname')]");
Dan Blows
  • 20,846
  • 10
  • 65
  • 96