gpt4 book ai didi

php - 在网页上显示 PHP 代码

转载 作者:行者123 更新时间:2023-11-29 05:25:32 26 4
gpt4 key购买 nike

我正在为 PHP 脚本创建一个库,我希望能够在 html 网页上显示 php 代码。

我看过使用 highlight_file();但这会显示整个页面

例如,如果我有一个名为 code.php 的页面,其中有一个 sql 查询(select code from table where sequence = $_GET["id"])- 示例然后我使用

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);
?>

我试过上面的代码,只是以纯文本显示代码

最佳答案

使用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_* 系列已被弃用。

关于php - 在网页上显示 PHP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20792351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com