Search code examples
phphtmlarrayssimple-html-dom

PHP get custom attribute value with DOM parser


I use simple dom parser to do some scrapping but failed to get the custom attribute (color). I was able to get others value like the h3's inner text.

My dom is simple it look like this

<article data-color="red">
<h1>Hi </h1>
</article>
<article data-color="blue">
<h1>Hi 2</h1>
</article>
<article data-color="gold">
<h1>Hi 3</h1>
</article>

My code so far

 $dom = $html->find('article');

 $arr = array();

foreach ($dom as $data) {
    if(isset($data->find('h3',0)->plaintext)){
        $h3 = $data->find(h3',0)->plaintext;
    }
}

    $arr[] = array(
        "title" => $h3,
    /* "color" => $color */
    );

echo json_encode(array_values($arr));

Solution

  • If you're afterthe data attribute property and since the DOM elements attributes are considered properties of that simple-html-dom object, just treat hyphenated properties as usual with a curly brace:

    $object->{'property-with-a-hyphen'}
    

    So when you apply this in your code:

    foreach($dom as $data) {
    
        $color = '';
        if(isset($data->{'data-color'})) {
            $color = $data->{'data-color'};
        }
    
        // array declarations below
        $arr[] = array(
            'color' => $color,
        );
    }