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="">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="">4</a></li></ul>";
        $oDocumentModel = new simple_html_dom();
        $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=''>4</a></li></ul>";
$oDocumentModel = new simple_html_dom();
$ul = $oDocumentModel->find('ul',0);

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

Or you can use lastChild() just go through the

Answer by Starx

You can extract the link this way.

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


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