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

时间:2014-07-18 12:08:45

标签: php wordpress dom if-statement

我有一个逻辑问题,但没有解决方案。 我有一个脚本,检查字符串是否包含<h3>并显示它们。 内容从数据库流入。

如果字符串不包含任何<h3>,则会产生错误。 我尝试使用if / else语句修复此问题,该语句检查字符串是否包含<h3> 如果它执行了脚本,则会抛出一条消息。 但由于某种原因,这不起作用。

以下是代码:

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

} }

希望任何人都可以为我提供正确的方向:-) 微米。

2 个答案:

答案 0 :(得分:0)

所以可能改变行:

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

   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
   }

因为在你的代码中,任何地方都没有if语句。

答案 1 :(得分:0)

你的问题可能是

的结果
$content = $dom->getElementsByTagname($tag);

因为如果没有结果可能会返回false或emtpy数组,因此无法进行更改,因此请进行简单的检查

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

应该足够了

如果没有,var_dump($ content)并查看它是什么