Simple dom php parse get custom data attribute value
Asked Answered
T

4

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.

Tayyebeb answered 7/10, 2014 at 16:8 Comment(4)
Your code makes no sense at all, you probably want to do this with javascript.Industrious
@JelleKeizer why? If u wonder why 1 element need a foreach, actually that is just an exampleTayyebeb
the question is straight to the point, how to get custom data attribute value in simple php dom parser.Tayyebeb
Sorry was misreading it, did you try getAttribute('data-a');Industrious
P
6

Why not just use the well-documented, built in, DOM extension?

Example:

$html = '<div class="something" data-a="abc">ddsf</div>';

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$nodes = $xpath->query('//div[@class="something"]/@data-a');
foreach ($nodes as $node) {
    var_dump($node->value);
}

Output:

string(3) "abc"
Pentyl answered 8/10, 2014 at 7:37 Comment(0)
S
3

It looks like this:

$dom->find('div[data-a]',0)->{'data-a'}
Saddlebag answered 8/10, 2014 at 1:38 Comment(3)
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'}Tayyebeb
No, the 0 means the first match. Without the 0 you get an array.Saddlebag
I couldn't for the life of me find this in the docs. Thank you so much!Devote
S
2

use

foreach($html->find('button') as $element) 
   echo $element->{'data-coupon'};
Schear answered 2/6, 2016 at 17:57 Comment(0)
P
1

Use xpath

Should be something like this:

foreach ($dom->xpath('/div[@data-a]') as $item) {
    ...
}
Prognosticate answered 7/10, 2014 at 16:13 Comment(2)
are you sure? this is like getting the right element, is this the way u get the value the custom attr?Tayyebeb
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'}Prognosticate

© 2022 - 2024 — McMap. All rights reserved.