Php 在同一页上按ID包括文件
有办法做到这一点吗 包括文件:Php 在同一页上按ID包括文件,php,html,Php,Html,有办法做到这一点吗 包括文件: <?php $_GET["id"]; case "fruits": include 'fruits.php'; ?> fruits.php: <?php $id = 'fruits'; echo 'hello fruits'; ?> 我想按包含文件中指定的ID包含文件。 谢谢您的帮助。您的代码非常不完整,但这里有一个解决问题的尝试 <?php // Get the ID parameter and change it to a s
<?php
$_GET["id"];
case "fruits": include 'fruits.php';
?>
fruits.php:
<?php
$id = 'fruits';
echo 'hello fruits';
?>
我想按包含文件中指定的ID包含文件。
谢谢您的帮助。您的代码非常不完整,但这里有一个解决问题的尝试
<?php
// Get the ID parameter and change it to a standard form
// (Standard form is all lower case with no leading or trailing spaces)
$FileId = strtolower(trim($_GET['id']));
// Check the File ID and load up the relevant file
switch( $FileId ){
case 'fruits':
require('fruits.php');
break;
case 'something_else':
require('something_else.php');
break;
/* ... your other test cases... */
default:
// Unknown file requested
echo 'An error has occurred. An unknown file was requested.';
}
?>
或者,如果您有一长串可能的文件,我建议您:
<?php
// Get the ID parameter and change it to a standard form
// (Standard form is all lower case with no leading or trailing spaces)
$FileId = strtolower(trim($_GET['id']));
// Array of possible options:
$FileOptions = array('fruits', 'something_else', 'file1', 'file2' /* ... etc... */);
// Check if FileId is valid
if(in_array($FileId, $FileOptions, true)){
// FileId is a valid option
$FullFilename = $FileId . '.php';
require($FullFilename);
}else{
// Invalid file option
echo 'An error has occurred. An unknown file was requested.';
}
?>
带有大量事例的Switch语句可能会变长,并且会降低可读性。因此,第二种解决方案使用数组,in_数组函数减少了代码长度。这还允许您轻松查看/管理允许的文件。首先修复PHP中的拼写错误和语法错误,然后尝试研究$id和$\u GET['id']之间的差异。如果$\u GET[id]是hello,它应该包含“hello.PHP”或什么?完成。我不确定$\u GET是否仅用于表单处理或从单独的文件中获取任何值。@Snorax:它应该包括id为hello或其他任何文件。您的问题非常复杂。。古怪的您基本上想这样做:如果$_GET['fruits']='fruits'{include'fruits.php';}或者什么?但是使用案例。