Zagloo
Zagloo

Reputation: 1387

PHP - Extract attributes and text from string for each <div>

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;

Upvotes: 1

Views: 150

Answers (1)

sym
sym

Reputation: 357

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
}

Upvotes: 1

Related Questions