Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find tag name using phpquery?

I am using phpquery to extract some data from a webpage. I need to identify the menu of the page. My implementation is to find each element that has sibilings > 0 and last-child is an "a". My code is:

foreach($this->doc['*'] as $tagObj){
$tag = pq($tagObj);
if(count($tag->siblings()) > 0){
    if($tag->find(":last-child")->tagName  === "a")
        echo trim(strip_tags($tag->html())) . "<br/>";
    }
}

However, I am not getting any output because of

$tag->find(":last-child")->tagName

which isn't returning anything. What would be the reason for this?

like image 904
Ahmad Avatar asked Jul 27 '15 05:07

Ahmad


2 Answers

I don't know this library but perhaps something like this

$siblings = $tag->siblings();
if (($siblingCount = count($siblings)) && $siblings[$siblingCount - 1]->tagName === 'a') {
    echo ...
}
like image 78
Phil Avatar answered Sep 27 '22 16:09

Phil


You can do it in reverse check for a:last-child :

For example :

foreach($this->doc['*'] as $tagObj){
$tag = pq($tagObj);
if(count($tag->siblings()) > 0){
    if($tag->find("a:last-child"))
        echo trim(strip_tags($tag->html())) . "<br/>";
    }
}

This will check for the a tag of last-child and you can get its content easily. May this help you.

like image 23
Bhavin Solanki Avatar answered Sep 27 '22 17:09

Bhavin Solanki