[英]PHP Pulling content from a DIV using switch statement
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. 我已经在自己的网站上设置了一个部分,根据所调用的DIV ID切换出内容,但是如果变量不在URL中,则初始的“值”会导致错误。
the error i get: Undefined index: item
我得到的错误:
Undefined index: item
item is my variable. 项目是我的变量。
My PHP is this: 我的PHP是这样的:
<?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
) 因此,如果我在URL末尾附加
?item=content1
,代码可以正常工作,但是,在初次访问时(末尾没有?item=
),我得到了上述错误( 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? 我该怎么办,如果有人访问说index.php,我不会收到错误,并抛出默认的内容?
Use an if
statement to check if the variable is set. 使用
if
语句检查是否设置了变量。 If not, set $item
to a default value. 如果不是,请将
$item
设置$item
默认值。
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. 而且,似乎不需要
switch/case
语句,因为除了用作explode
分隔符的情况以外,每种情况都是相同的。
$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. 最好使用
DOMDocument
和DOMXPath
而不是字符串匹配来解析您的内容。
You could also use the shorthand if statement for this if you want to get really fancy. 如果您真的想花哨的话,也可以使用简写的if语句 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.