User1
User1

Reputation: 71

Echoing only a div with php

I'm attempting to make a script that only echos the div that encolose the image on google.

$url = "http://www.google.com/";
$page = file($url);

foreach($page as $theArray) {
echo $theArray;
}

The problem is this echos the whole page. I want to echo only the part between the <div id="lga"> and the next closest </div> Note: I have tried using if's but it wasn't working so I deleted them

Thanks

Upvotes: 1

Views: 102

Answers (2)

Maerlyn
Maerlyn

Reputation: 34107

Use the built-in DOM methods:

<?php

$page = file_get_contents("http://www.google.com");

$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($page);
libxml_use_internal_errors(false);

$domx = new DOMXPath($domd);
$lga = $domx->query("//*[@id='lga']")->item(0);

$domd2 = new DOMDocument();
$domd2->appendChild($domd2->importNode($lga, true));

echo $domd2->saveHTML();

Upvotes: 2

dmcnelis
dmcnelis

Reputation: 2923

In order to do this you need to parse the DOM and then get the ID you are looking for. Check out a parsing library like this http://simplehtmldom.sourceforge.net/manual.htm

After feeding your html document into the parser you could call something like:

$html = str_get_html($page); 
$element = $html->find('div[id=lga]'); 
echo $element->plaintext;

That, I think, would be your quickest and easiest solution.

Upvotes: 2

Related Questions