<div id="score">
<div class="name"><span style="width:68%">A</span></div>
<span class="roll">1</span>
<div class="name"><span style="width:60%">B</span></div>
<span class="roll">2</span>
<div class="name"><span style="width:56%">C</span></div>
<span class="roll">3</span>
</div>
i want to iterate over each span of div.name but i am not getting to next span.roll tag I have used this code yet and also check the condition if A is available then 1 display and same as above name to check.
<?php
include("simple_html_dom.php");
$obj = new simple_html_dom();
foreach ($obj->find('div[id=score]') as $factor)
{
$item = $factor->find('div[class=name] span')->plaintext;
if(trim($item) == 'A')
{
$a = $factor->find('span[class=roll]',0)->plaintext;
}
if(trim($item) == 'B')
{
$b = $factor->find('span[class=roll]',1)->plaintext;
}
if(trim($item) == 'C')
{
$c = $factor->find('span[class=roll]',2)->plaintext;
}
$final_array['overalldata'] = array
(
'a'=> $a,
'b' => $b,
'c' => $c,
);
}
print_r($final_array);
die;
?>
Any body having any idea please help to sort it out. Thanks
As an alternative, since you're targeting that ID, you don't need to have a foreach
on the parent element, just get it outright.
Then you apply the foreach
on its children, getting the names and rolls.
Here's the idea:
$final_array['overalldata'] = null; // initialize
$factor = $obj->find('div[id=score]', 0); // get the parent
foreach ($factor->find('div[class=name]') as $item) { // each item of the parent
$name = $item->find('span', 0)->innertext; // get the name
$roll = $item->next_sibling()->innertext; // get the next sibling which is the roll
$final_array['overalldata'][$name] = $roll; // and assign it (push it inside the array)
}
print_r($final_array);
So basically, to get the name
just target the child inside each div
, and then, to target the roll
(which is the sibling of each div
), just use ->next_sibling()
method.
Sidenote: If I were you, I'd stick to DOM
. It's already built-in inside PHP, no need to include any third party libraries.