Skip to content Skip to sidebar Skip to footer

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:

Some title here

Lorem ip

Solution 1:

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].

Solution 2:

You could try something like:

preg_split("/<h4>.+</h4>/i", $html);

Solution 3:

This should do what you want -- though I'm sure there are other (and possibly better) ways

$aHTML = explode("<h4>", $cHTML);
foreach ($aHTMLAS$nPos => $cPanel) {
  if ($nPos > 0) {
    $aPanel = explode("</h4>", $cPanel);
    $cHeader = "<h4>" . $aPanel[0] . "</h4>";
    $cPanelContent = $aPanel[1];
  }
}

It doesn't put it in the array format you stipulated -- though you could do that yourself inside the loop. Otherwise your content could be output/constructed inside the loop.

Edit: Added the h4 and /h4 back in for completeness

Solution 4:

You can use the same code with little small changes, And it will apply to all kinds of HTML not normal ones.

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

        $content = [];
        $value = '';

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

           while(($node = $node->nextSibling) && $node->nodeName !== 'h4') {
              $value .= $dom->saveHTML($node);
           }

           $content[$k]['value'] = $value;
        }
        
        echo'<pre>';
        print_r($content);die;

Post a Comment for "Php Split Html String Into Array"