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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog