问题
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?
回答1:
I don't know this library but perhaps something like this
$siblings = $tag->siblings();
if (($siblingCount = count($siblings)) && $siblings[$siblingCount - 1]->tagName === 'a') {
echo ...
}
回答2:
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:
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);
回答4:
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
.
来源:https://stackoverflow.com/questions/31645478/how-to-find-tag-name-using-phpquery