网站开发日志

2008年12月17日星期三

分享家:Addthis中国

jQuery 显示PHP源代码

我在上篇文章里介绍了如何运用jQuery来显示页面源代码,该方法简洁易用,但是有个缺点:不能显示动态源代码。例如,你用它来显示PHP代码,得到的实际上是PHP被执行后产生的HTML代码。本文将介绍如何显示PHP代码本身。其实要显示PHP代码并不难,PHP库就自带有下面两种方法,它们不但可以显示PHP代码,而且还具有语法加亮的功能。

  • highlight_file (string $filename [, bool $return]) //输入为文件
  • highlight_string (string $str [, bool $return]) //输入为字符串

默认情况下,以上两种方法直接打印输出,也就是说你不用加echo。如果你想要让它们输出结果做为返回值,你可以加入第二个参数,例如:$result = highlight_file ($file, true);

本文要介绍的方法用到highlight_string,步骤如下:

1.创建一个PHP文件,这里命名为hlight.php

<?php
$file = isset($_POST['file'])? $_POST['file'] : "";
$content = file_get_contents($file);
highlight_string($content);
?>

2. 对上篇文章里的Javascript稍作修改,如下:

<script type="text/javascript">
  $( document ) . ready ( 
   function() {
    $('a.sourcecode').each (
      function( i ) {
        $( this ).after( '<pre class="sourcecode"></pre>' );
      }
    )
    $( 'pre.sourcecode' ).hide();
    $('a.sourcecode').toggle ( 
      function() {
      if( !this.old ){
      this.old = $(this).html();
      }
      $(this).html('隐藏代码');
        showCode(this);
      },
      function() {
        $(this).html(this.old);
        $(this.nextSibling).hide();
      }
    )
    function showCode(o){
      if(!o.nextSibling.hascode){
       var rel = o.href.split("/");
       $(o.nextSibling).load("hlight.php",{"file":rel[rel.length-1]});  
          o.nextSibling.hascode=true;
      }
      $(o.nextSibling).show();
    }
  }
)
</script>

3. 链接代码:

<a href="simple-test-system.php" class="sourcecode">
显示源代码(直接显示php代码)</a>
<!--href里php文件必须是和页面在同一个路径下-->

实际上,这种方法也适用于显示HTML,Javascript,CSS等代码。当然如果你不想显示PHP代码,则必须使用上篇文章中介绍的方法。

演示:显示php代码

标签: , , ,

相关文章:

0 条评论:

发表评论

指向此帖子的链接: