How to find tag name using phpquery?

2019-06-15 09:53发布

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?

4条回答
可以哭但决不认输i
2楼-- · 2019-06-15 10:25

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.

查看更多
乱世女痞
3楼-- · 2019-06-15 10:30

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

$siblings = $tag->siblings();
if (($siblingCount = count($siblings)) && $siblings[$siblingCount - 1]->tagName === 'a') {
    echo ...
}
查看更多
虎瘦雄心在
4楼-- · 2019-06-15 10:31

Because phpQueryObject returned by pq implements the Iterator and uses a public array $elements to store all elements, we need to get the element using the get() function, which returns a DOMElement that is has the tagName and nodeName properties:

$q = phpQuery::newDocumentHTML('<div><span class="test-span">Testing test</span></div>');
echo $q->find('.test-span')->get(0)->tagName; // outputs "span"
//echo $q->find('.test-span')->get(0)->nodeName; // outputs "span"

Both properties will output the tag name that has the test-span class which of course is span.

查看更多
男人必须洒脱
5楼-- · 2019-06-15 10:41

Maybe you should use :last instead of :last-child

According to the library Google Page:

$li = null;
$doc['ul > li']
        ->addClass('my-new-class')
        ->filter(':last') // <--- :last
                ->addClass('last-li')
// save it anywhere in the chain
                ->toReference($li);
查看更多
登录 后发表回答