doudichu1358 2014-07-18 12:08
浏览 58
已采纳

如果/ 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.

  • 写回答

2条回答 默认 最新

  • dongzhi4470 2014-07-18 12:22
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题