Skip to content
Advertisement

PHP Split html string into array

I hope I can get some help from you guys.

This is what I’m struggling with, I have a string of HTML that will look like this:

<h4>Some title here</h4>
<p>Lorem ipsum dolor</p>
(some other HTML here)

<h4>Some other title here</h4>
<p>Lorem ipsum dolor</p>
(some other HTML here)

I need to split all the <h4> from the rest of the content, but for example the content after the first <h4> and before the second <h4> needs to be related to the first <h4>, something like this:

Array {
       [0] => <h4>Some title here</h4>
       [1] => <p>Lorem ipsum dolor</p>
}

Array {
       [0] => <h4>Some other title here</h4>
       [1] => <p>Lorem ipsum dolor</p>
}

This is to build an accordion (quite difficult to explain why I’m doing this way, but it has to be this way), and the <h4> will be the accordion panel headings and when clicked it will expand and show the content associated with them.

I hope I made my problem clear, let me know of your thoughts and how should I do this the better way.

I was looking into DOMDocument, but I also tried with explode() but with no success.

I have this working with JavaScript but I need to achieve the same thing with PHP, but it’s quite complicated to play with the DOM with PHP.

Thank you in advance.

Advertisement

Answer

I was able to do what I wanted following the example that Derek S gave me.

This was the result:

$html_string = 'HTML string';
$dom = new DOMDocument();
$dom->loadHTML($html_string);

foreach($dom->getElementsByTagName('h4') as $node) {
   $title = $dom->saveHTML($node);
   $content[$title] = array();

   while(($node = $node->nextSibling) && $node->nodeName !== 'h4') {
      $content[$title] = $dom->saveHTML($node);
   }
}

This will save the titles inside $title and the correspondent content inside $content[$title].

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement