dongnan1899 2018-02-09 23:14
浏览 54
已采纳

PHP使用switch语句从DIV中提取内容

I've set up a section on my site, to switch out content, based on the DIV ID called, but the initial "value" results in an error, if the variable isn't in the url.

the error i get:Undefined index: item

item is my variable.

My PHP is this:

<?php
    $url = 'file.php';
    $content = file_get_contents( $url );


    $item = $_GET[ 'item' ];
    switch ( $item ) {
        case "content1":
            $start = explode( '<div id="content1">', $content );
            $end = explode( "</div>", $start[ 1 ] );
            echo $end[ 0 ];
            break;

        case "content2":
            $start = explode( '<div id="content2">', $content );
            $end = explode( "</div>", $start[ 1 ] );
            echo $end[ 0 ];
            break;

        case "content3":
            $start = explode( '<div id="content3">', $content );
            $end = explode( "</div>", $start[ 1 ] );
            echo $end[ 0 ];
            break;

        default:
            $start = explode( '<div id="content1">', $content );
            $end = explode( "</div>", $start[ 1 ] );
            echo $end[ 0 ];
    }?>

So the code works fine if I append ?item=content1 at the end of my url, however, on initial visit (without the ?item= at the end) i get the above error ( Undefined index: item)

What can I do so that if someone visits say index.php I won't get the error, and throw up the default called content?

  • 写回答

1条回答 默认 最新

  • douningzhi1991 2018-02-09 23:31
    关注

    Use an if statement to check if the variable is set. If not, set $item to a default value.

    if (isset($_GET['item'])) {
        $item = $_GET['item'];
    } else {
        $item = 'content1';
    }
    

    Also, there doesn't seem to be a need for the switch/case statement, since every case is identical except for what you're using as the explode delimiter.

    $delimiter = '<div id="' . $item . '">';
    $start = explode($delimiter, $content);
    $end = explode("</div>", $start[ 1 ] );
    echo $end[0];
    

    It would probably be better to use DOMDocument and DOMXPath instead of string matching to parse your content.

    You could also use the shorthand if statement for this if you want to get really fancy.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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