May 29, 2012

How to get last li's anchor tag with simple dom html in php

Question by Ravi Kotwani

I am crawling a web with the help of simple dom in PHP.

I am getting following html with the help curl:

<ul><li>1</li><li>2</li><li>3</li><li><a href="http:abc.com">4</a></li></ul>

Now, I need to href (link) of anchor tag which is in the last li of this ul with the help of simple dom object. Please provide me syntax how can I do this?

I have tried with the following code but i am not able to find the last li…

require_once 'simple_html_dom.php';
        $html = "<ul><li>1</li><li>2</li><li>3</li><li><a href="http:abc.com">4</a></li></ul>";
        $oDocumentModel = new simple_html_dom();
        $oDocumentModel->load($html);
        $ul = $oDocumentModel->find('ul',0);

Answer by Sanjay

You can loop through the li and convert it in array and find the last element. if you have smaller set of li like…

require_once 'simple_html_dom.php';
$html = "<ul><li>1</li><li>2</li><li>3</li><li><a href='http:abc.com'>4</a></li></ul>";
$oDocumentModel = new simple_html_dom();
$oDocumentModel->load($html);
$ul = $oDocumentModel->find('ul',0);

$items = array();
foreach( $ul->find('li') as $li ){
    $items[] = $li->plaintext;
}
$last = end($items);
print_r($last);

Or you can use lastChild() just go through the http://simplehtmldom.sourceforge.net/manual_api.htm

Answer by Starx

You can extract the link this way.

$ul = $oDocumentModel->find('ul',0);
$a = $ul -> lastChild() -> find('a'. 0);
$href = $a -> href;
...

Please fill the form - I will response as fast as I can!