Search code examples
phpsimple-html-dom

How to get data from div class data using simple dom parser?


I'm trying to get the pic id and description from a class

<div class="pic" style="top:0px;left:0px;height:149px;" data= 
{"pic_id":"06e50224ab189";}" pic-descr=" this title " data-index="0">

....

</div>

how to find and get pic_id data and pic-descr ?


Solution

  • It's interesting because it looks like pic_id is broken json. We can still get the data with a regex:

    $str = <<<EOF
    <div class="pic" style="top:0px;left:0px;height:149px;" data='{"pic_id":"06e50224ab189";}' pic-descr=" this title " data-index="0">
    </div>
    EOF;
    
    $html = str_get_html($str);
    $div = $html->find('.pic', 0);
    
    if(preg_match('/:"(.*?)"/', $div->data, $m)){
      echo "pic_id is: " . $m[1] . "\n";
    }
    echo "pic-descr is: " . $div->{'pic-descr'} . "\n";
    

    If the json were not broken you could do: json_decode($div->data)->pic_id