如果/ Else $ dom-> loadHTML($ html);

I have a logical problem but no solution. I have a script that checks if a string contains <h3> and displays them. The content flows in from a database.

If the string doesn't contain any <h3> it produces an error. I tried to fix this with an if/else statement that checkes if the string contains <h3> If it does the script goed on else it throws an message. But this doesn't work for some reason.

Here's the code:

function getTextBetweenTags($tag, $html, $strict=0)
{
/*** a new dom object ***/
$dom = new domDocument;

/*** load the html into the object ***/

$dom->loadHTML($html);


/*** discard white space ***/
$dom->preserveWhiteSpace = false;

/*** the tag by its tag name ***/
$content = $dom->getElementsByTagname($tag);

/*** the array to return ***/
$out = array();
foreach ($content as $item)
{
    /*** add node value to the out array ***/
    $out[] = $item->nodeValue;
}
/*** return the results ***/
return $out;
}

global $post;
$post_id = $post->ID;
$html = get_post_field('post_content', $post_id);
$content = getTextBetweenTags('h3', $html);
$i=0;
echo '<ul>';
foreach( $content as $item )
{
    echo '<li><a href="#'.$i++.'">'.$item.'</a></li>';
}
echo '</ul>';
echo $after_widget; //Widget ends printing information

} }

Hope anyone can provide me with a kick in the right direction :-) M.

your problem probably is that the result of

$content = $dom->getElementsByTagname($tag);

cant be itarated over because it may return false or emtpy array if there are no results, so a simple check

if($content[0]){ 
   foreach...

should be enough

if not, var_dump($content) and look what it is

So probably change line:

$content = getTextBetweenTags('h3', $html);

into

   mb_internal_encoding('UTF-8');
   if (mb_strpos($html, 'h3') !== false) { 
      $content = getTextBetweenTags('h3', $html);
      // you may want to move here the rest of your code including foreach loop
   }
   else {
      $content = $html; // or anything you need here
   }

because in your code there is no if statement anywhere.