4

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));
0

1 Answer 1

3

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,
    );
}
Sign up to request clarification or add additional context in comments.

4 Comments

is this PHP or part of simple dom parser?
this is part of PHP, thats the way to access hypenated properties
@EltonJamie yes thats how you handle them, even with some like $data->{'@attributes'} or something like that, yeah, thats how you access them. im glad this shed some light
@EltonJamie, you might consider accepting the answer to make sure people in the future will see that this type of problem has been solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.