February 27, 2012

PHP Html Dom/Parser

Question by gir3191

i) I need to extract few elements from a html page using php.

ii) Am using html dom parser.

iii) I have been able to extract all **<a>**s, **<b>**s, **<li>**s, etc.

iv) How should I be able to extract elements of the type/enclosed within

**<td class = ""><a href = "">ABC</a></td>**

Anything using href, i.e. property of href

Note: I need to extract ABC

Answer by Starx

You will not get the entire structure using the DOM Parser.

You should use getAttribute() method for that purpose. Check here

Here is a simple example also

$markup = file_get_contents($someplace);
$dom = new DomDocument();
$dom -> loadHTML($markup);
$tds = $dom -> getELementsByTagName("td");
foreach($tds as $td) {
    echo $td -> getAttribute("class");
}

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!