【问题标题】:load part of an external site using curl?使用 curl 加载外部站点的一部分?
【发布时间】:2010-08-26 02:52:39
【问题描述】:

我正在为一所大学创建一个网站,我们必须在页面顶部包含该大学的主导航。我不想重新创建他们的导航,而是想动态加载它。

首先我认为我可以使用 iframe 并将其修剪为导航。

但是,当单击链接时,它会在该框架中打开,而我希望它在新窗口中。

所以,我的新计划是使用 curl (或者如果有人有建议的话,以其他方式)来拉入导航。解决这个问题的最好方法是什么? curl 相当新,所以我喜欢一些代码。

谢谢!

【问题讨论】:

    标签: php curl


    【解决方案1】:

    如果您想使用 cURL 检索它,您可以使用 cURL 网站上的这个示例:http://curl.haxx.se/libcurl/php/examples/simpleget.html

    或者,您可以使用 PHP 的 readfile 函数将文件(本地或外部)直接读取到页面中,或者使用 file_get_contents 函数将其加载到变量中(然后您可以在将其输出到页面之前对其进行操作)。

    【讨论】:

    • 抱歉,我无法访问此服务器上的代码,我需要将其从 html 站点中删除。
    • OK,那么您可以使用readfile function 将远程文件读入页面。这将比 cURL 更简单甚至更快。此外,您可以使用file_get_contents function 将 URL 读入变量,而不是直接将其输出到页面上。
    【解决方案2】:

    我最近在一个客户的现有网站上做了这个破解。

    在大学网站中创建一个“布局视图”,其中包含您想要的标题和导航。使正文为空,除了一个标志会告诉您的解析器脚本在哪里插入内容。

    <div class="nav">
        <!-- ... -->
    </div>
    <div class="body">
        <!-- Below is the flag -->
        {content} 
    </div>
    

    使用以下代码导入布局HTML,将页面HTML插入其中,然后输出

    // Variables
    $contentForLayout = '<p>This is the page content</p>'
    $pageTitle = 'Test Page';
    $layoutUrl = 'http://'.$_SERVER['HTTP_HOST'].'/unilayout'; // AFAIK, cURL like the host to be there
    
    // Get layout HTML
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $layoutUrl);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    ob_start();
    curl_exec($ch);
    curl_close($ch);
    $layoutHtml = ob_get_contents();
    ob_end_clean();
    
    // Insert your page HTML into the layout HTML
    $layoutHtml = str_replace('{content}', $contentForLayout, $layoutHtml);
    
    // Insert your page title into the layout HTML
    $layoutHtml = preg_replace('%<title>[^<]*</title>%si', '<title>'.h($pageTitle).'</title>', $layoutHtml);
    
    // Output
    print $layoutHtml;
    

    【讨论】:

      【解决方案3】:

      您可以尝试使用这个库 http://github.com/shuber/curl 并使用正则表达式或 html 解析器从 curl 响应正文中解析导航

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-02
        • 2015-05-16
        • 2016-06-22
        • 2012-09-16
        相关资源
        最近更新 更多