dongtuanzi1080 2012-12-30 05:26
浏览 23
已采纳

在ajax调用中处理php代码

I am using ajax on a website that calls a php script that then parses another page and returns the part of the page that I want to display. I have used this technique in the past and it works well, except this time the part of the page that is being returned has some php code in it and it is being returned raw with out the php code being processed.

Here is the php script that is doing the parseing and returning the results.

require_once('simple_html_dom.php');
$dom = new simple_html_dom;

if(isset($_GET['url']))  {
    $url = $_GET['url'];
    $html = file_get_html($url);
    /*get contents*/
    $contents = $html->getElementById('content');
    echo $contents;
}

As I mentioned what is being returned in $contents is being returned raw with out the php code inside the $contents string being processed, how can I get it to process the php code before returning the $contents string?

Thank you in advance for your help.

  • 写回答

1条回答 默认 最新

  • dongshadu2546 2012-12-30 07:22
    关注

    Parsing the HTML generated by another PHP script is rather hackish. If you are developing a new site, at a minimum, you should divide your PHP script into functions and then, for AJAX requests, only call the necessary functions.

    Even if you are working on an existing, complex site, keep in mind that jQuery's .load() allows you to insert a specific fragment of the server's response into the document, discarding the rest:

    $('#content').load('script.php #content');
    

    That said, what you are asking about is possible:

    • PHP's output control functions allow you to capture a script's output as a string, which you can parse using str_get_html(). To make this work, you would have to include the existing PHP script. Note that any script you include will have access to global functions and variables, superglobals, and classes.

      Warning: Make sure you check the requested filename against a whitelist of specific files to prevent file inclusion attacks. Merely blacklisting URLs and disabling allow_url_fopen are not sufficient to protect your site.

      ob_start();
      require $filename; // might have to be outside of a function
      $html = str_get_html(ob_get_clean());
      
    • Alternatively, you could have the AJAX script make its own HTTP request using either file_get_contents() or cURL (specifying an absolute URL, not a filename). Unless you configure your web server otherwise, this internal request would show up in your web server's access log as coming from 127.0.0.1 or your web server's IP address.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!