I am using PHP Domdocument to load my html. In my HTML, I have class="smalllist" two times. But, I need to load the first class elements.
Now, My PHP Code is
$d = new DOMDocument();
$d->validateOnParse = true;
@$d->loadHTML($html);
$xpath = new DOMXPath($d);
$table = $xpath->query('//ul[@class="smalllist"]');
foreach ($table as $row) {
echo $row->getElementsByTagName('a')->item(0)->nodeValue."-";
echo $row->getElementsByTagName('a')->item(1)->nodeValue."
";
}
which loads both the classes. But, I need to load only one class with that name. Please help me in this. Thanks in advance.
This is my final code:
$d = new DOMDocument();
$d->validateOnParse = true;
@$d->loadHTML($html);
$xpath = new DOMXPath($d);
$table = $xpath->query('//ul[@class="smalllist"]');
$count = 0;
foreach($table->item(0)->getElementsByTagName('a') as $anchor){
$data[$k][$arr1[$count]] = $anchor->nodeValue;
if( ++$count > 1 ) {
break;
}
}
Working fine.
DOMXPath
returns a DOMNodeList
which has a item()
method. see if this works
$table->item(0)->getElementsByTagName('a')->item(0)->nodeValue
edited (untested):
foreach($table->item(0)->getElementsByTagName('a') as $anchor){
echo $anchor->nodeValue . "
";
}
You can put a break
within the foreach
loop to read only from the first class. Or, you can do foreach ($table->item(0) as $row) {
...
Code:
$count = 0;
foreach($table->item(0)->getElementsByTagName('a') as $anchor){
echo $anchor->nodeValue . "
";
if( ++$count > 2 ) {
break;
}
}
another way rather than using break (more than one way to skin a cat):
$anchors = $table->item(0)->getElementsByTagName('a');
for($i = 0; $i < 2; $i++){
echo $anchor->item($i)->nodeValue . "
";
}