tags:

views:

66

answers:

3

i am trying to grab links from the Google search page. i am using the be below xpath to

//div[@id='ires']/ol[@id='rso']/li/h3/a/@href

grab the links. xPather evaluates it and gives the result. But when i use it with my php it doesn't show any result. Can someone please tell me what I am doing wrong? There is nothing wrong with the cURL.

below is my code

$dom = new DOMDocument();
@$dom->loadHTML($result);

$xpath=new DOMXPath($dom);
$elements = $xpath->evaluate("//div[@id='ires']/ol[@id='rso']/li/h3/a");

foreach ($elements as $element)
{
   $link  = $element->getElementsByTagName("href")->item(0)->nodeValue;

   echo $link."<br>";
}

Sample Html provided by Robert Pitt

<li class="g w0">
    <h3 class="r">
       <a href="" class="l"><em>LINK</em></a>
    </h3>
    <button class="ws" title=""></button>
    <div class="s">
        META
    </div>
</li>
A: 

Theres no element called href, thats an attribute:

$link  = $element->getElementsByTagName("href")->item(0)->nodeValue;

You can just use

$link  = $element->getAttribute('href');
RobertPitt
I tried it but it didn't show any result..
LiveEn
can you do `var_dump($element);` and show me what it says?
RobertPitt
Its weird.. Nothing is displayed.. Looks like not iterating through the foreach loop. Even when i try to echo a simple message it’s not displayed.
LiveEn
+1  A: 

You can make life simpler by using the original XPath expression that you quoted:

//div[@id='ires']/ol[@id='rso']/li/h3/a/@href

Then, loop over the matching attributes like:

$hrefs = $xpath->evaluate(...);
foreach ($hrefs as $href) {
    echo $href->value . "<br>";
}

Be sure to check whether any attributes were matched (var_dump($hrefs->length) would suffice).

salathe
i tried it and nothing seems to be displayed.
LiveEn
You didn't just copy/paste the code did you?
salathe
nope..when i try a dump var_dump($hrefs) outside the loop i get object(DOMNodeList)#2 (0) { } .. But when i try a var_dump($href); inside the foreach its just blank.
LiveEn
Are you getting any matching attributes (see my answer)?
salathe
A: 

did you try

$element->getElementsByTagName("a")

instead of

$element->getElementsByTagName("href")
Dennis Knochenwefel