1

I have a string $value which looks like that:

'<div id='1' data-AAA='something1' data-BBB='something2'>My</div><div id='5' data-AAA='something5' data-BBB='something6'>Web</div>
...'

In PHP, I would like for each <div>, extract all data attributes (here id, data-AAA and data-BBB) and also the text, and then put them into an array like that:

Array
  [0]
     ID => 1
     data-AAA => something1
     data-BBB => something2
     text => My
  [1]
     ID => 5
     data-AAA => something5
     data-BBB => something6
     text => Web

Is it possible to extract all those informations from a string with a loop ? being debutant, I have no idea how to do that for a string...

EDIT 1

thanks to the DOM doc (http://php.net/manual/en/class.domdocument.php) given in answers, I tried this and that works !

        $dom = new DOMDocument;
        $dom->loadHTML($value);
        foreach ($dom->getElementsByTagName('div') as $ST) {
            $valueID = $ST->getAttribute('id');
            $valueDataTimeStart = $ST->getAttribute('data-AAA');
            $valueDataTimeStart = $ST->getAttribute('data-BBB');
            $valueDataTimeEnd = $ST->getAttribute('id');
            var_dump($valueID);
            var_dump($valueDataTimeStart);
            var_dump($valueDataTimeEnd);
        }die;
3
  • 2
    DOMDocument Commented Mar 30, 2015 at 13:08
  • 2
    DAM DAM DOM! (<- I think you are looking for this :) Commented Mar 30, 2015 at 13:08
  • Thanks to you ! This is what I seached :) ! Commented Mar 30, 2015 at 13:29

1 Answer 1

1

something like this :

$dom = new DOMDocument();
$dom->loadHTML($l_sContent);
$l_aDiv = $dom->getElementsByTagName("div");
foreach ($l_aDiv as $l_aOneDiv) {
 // search attributes on $l_aOneDiv
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes thanks, I tried that 5 minutes ago and it works :)

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.