5

HTML:

<div class="something" data-a="abc">ddsf</d>

PHP:

foreach ($dom->find('.something[data-rel]') as $this) {
    var_dump($this->attr());
}

I tried this but error. Couldn't find any info on its documentation. I want to get the data-a's value which is abc.

4
  • 1
    Your code makes no sense at all, you probably want to do this with javascript. Commented Oct 7, 2014 at 16:11
  • @JelleKeizer why? If u wonder why 1 element need a foreach, actually that is just an example Commented Oct 7, 2014 at 16:59
  • 1
    the question is straight to the point, how to get custom data attribute value in simple php dom parser. Commented Oct 7, 2014 at 16:59
  • Sorry was misreading it, did you try getAttribute('data-a'); Commented Oct 7, 2014 at 18:16

3 Answers 3

3

It looks like this:

$dom->find('div[data-a]',0)->{'data-a'}
Sign up to request clarification or add additional context in comments.

3 Comments

how bout $dom->find('div[data-a]')->{'data-a'} ? the zero is optional right? because assume I can do like this $dom->find('.panel [data-a]')->{'data-a'}
No, the 0 means the first match. Without the 0 you get an array.
I couldn't for the life of me find this in the docs. Thank you so much!
2

use

foreach($html->find('button') as $element) 
   echo $element->{'data-coupon'};

Comments

1

Use xpath

Should be something like this:

foreach ($dom->xpath('/div[@data-a]') as $item) {
    ...
}

2 Comments

are you sure? this is like getting the right element, is this the way u get the value the custom attr?
No, this way you find and loop through all 'div' elements that have "data-a" attribute. To get the value of this attribute you just need to access $item->attributes()->{'data-a'}

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.