fork(2) download
  1. <?php
  2.  
  3. $html = "<div id='gallery-7222-1' class='gallery galleryid-7222 gallery-columns-3 gallery-size-thumbnail'>";
  4.  
  5. // grab all containers from the HTML.
  6. $dom_doc = new DOMDocument();
  7.  
  8. /*
  9.  * $html here can be the example I posted above.
  10.  * LIBXML_HTML_NOIMPLIED and LIBXML_HTML_NODEFDTD are used
  11.  * to avoid adding a doctype and wrapping the whole output in HTML tags.
  12.  */
  13. $dom_doc->loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
  14.  
  15. // Let's look for lists and divs.
  16. $ul_tags = $dom_doc->getElementsByTagName( 'ul' );
  17. $div_tags = $dom_doc->getElementsByTagName( 'div' );
  18.  
  19. /*
  20.  * Loop through each ul, and add the data.
  21.  * I do more things in there, like checking for what class the ul has,
  22.  * but I've simplified things here.
  23.  */
  24. foreach ( $ul_tags as $ul_tag ) {
  25. $ul_tag->setAttribute( 'data-foo', 'bar' );
  26. }
  27.  
  28. /*
  29.  * Loop through each div, and add the data.
  30.  * I do more things in there, like checking for what class the div has,
  31.  * but I've simplified things here.
  32.  */
  33. foreach ( $div_tags as $div_tag ) {
  34. $div_tag->setAttribute( 'data-foo', 'bar' );
  35. }
  36.  
  37. // Save our updated HTML.
  38. $html = $dom_doc->saveHTML();
  39.  
  40. // Let's see it here.
  41. var_dump( $html );
Success #stdin #stdout 0.01s 24540KB
stdin
Standard input is empty
stdout
string(119) "<div id="gallery-7222-1" class="gallery galleryid-7222 gallery-columns-3 gallery-size-thumbnail" data-foo="bar"></div>
"