我正在为PHP脚本创建一个库,我希望能够在html网页上显示php代码。
我看过使用highlight_file();但这将显示整个页面
例如,如果我有一个名为code.php的页面,它在(select code from table where sequence = $_GET["id"]
)上有一个sql查询 - 示例那么我使用
Highlight_file('code.php?id=123');
这将有效,但也会显示我不想显示的选择查询。我只想显示数据库中的代码(代码列)
如何使用正确的颜色和格式等显示数据库中的代码
更新:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id, $conn)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query,$conn);
$code = mysql_fetch_array($rs);
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id'], $conn);
?>
我已经尝试过上面的代码,它只是以纯文本显示代码
答案 0 :(得分:3)
使用highlight_string
功能,如下所示:
<?php
highlight_string($code);
?>
其中$code
是您从SQL查询中获取的代码。
您可以围绕此创建一个函数(沿着以下几行):
<?php
function highlight_code_with_id($id, $mysqli) {
$query = $mysqli->query("select code from table where sequence = '$id'");
$code = current($query->fetch_assoc());
return highlight_string($code);
}
// and, use it like this:
echo highlight_code_with_id($_GET['id'], $mysqli);
<强>更新强>
您的代码有点不正确,您可以使用:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query);
$code = mysql_fetch_assoc($rs); // change is in this line
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id']);
?>
请注意,您不需要在函数中包含$conn
,也可以省略它。另请注意,您应使用mysqli->*
系列函数,因为mysql_*
系列已被弃用。
答案 1 :(得分:0)
Perhaps this would work for you.
这篇文章最初是针对HTML的,但上面链接的答案显示了一个使用PHP的例子。