Search code examples
phpsimple-html-domdynamic-arrays

Inconsistent records with simple_html_dom


I am trying to use simple_html_dom and PHP to pick records from a page that are in the form: name/job/address. The problem is that not every record stores a value for 'job'. Say a page has 10 records, and only 2 of them record a person's job, then if I use something like the following:

foreach($html->find('span[class="name"]') as $e) {
    $name[]=$e->innertext;
}

foreach($html->find('span[class="job"]') as $e) {
    $job[]=$e->innertext;
}

foreach($html->find('span[class="address"]') as $e) {
    $address[]=$e->innertext;
}

then when I come to access the three arrays I find the $job array is only two records long, while names and addresses are 10 long, and so I don't know which of the 10 names those 2 jobs 'belong' to. Is there a way of keeping the arrays 'in step' with each other, or some other way of keeping records coherently intact here?

Thank you.


Solution

  • Then simply insert a null value when Job node is empty!!

    foreach($html->find('span[class="job"]') as $e) {
        $value=$e->innertext;
    
        if (empty($value))
            $job[] = null;
        else
            $job[] = $value;
    }
    

    Or using the shorthand if-else version $job[] = (empty($value) ? null : $value);