0

我正在尝试访问然后打印(或只是能够使用)使用 PHP 的任何网站的源代码。我不是很有经验,现在我想我可能需要使用 JS 来完成这个。到目前为止,下面的代码访问网页的源代码并显示网页......我想要它做的是显示源代码。本质上,也是最重要的,我希望能够将源代码存储在某种变量中,以便以后使用。并最终逐行阅读 - 但这可以稍后解决。

$url = 'http://www.google.com';
function get_data($url) 
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
echo get_data($url); //print and echo do the same thing in this scenario.
4

5 回答 5

2

考虑使用file_get_contents()而不是curl. 然后,您可以通过将每个左括号 (<) 替换为&lt;然后将其输出到页面来在页面上显示代码。

<?php
$code = file_get_contents('http://www.google.com');
$code = str_replace('<', '&lt;', $code);
echo $code;
?>

编辑:
看起来 curl 实际上比 FGC 快,所以忽略这个建议。我的帖子的其余部分仍然有效。:)

于 2012-12-27T22:38:31.667 回答
1

我重写了你的函数。该函数可以带行或不带行返回源。

<?php 
function get_data($url, $Addlines = false){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    $content = curl_exec($ch);
    $content = htmlspecialchars($content); // Prevents the browser to parse the html

    curl_close($ch);

    if ($Addlines == true){
        $content = explode("\n", $content);
        $Count = 0;
        foreach ($content as $Line){
            $lines = $lines .= 'Line '.$Count.': '.$Line.'<br />';
            $Count++;
        }
        return $lines;
    } else {
        $content = nl2br($content);
        return $content;
    }
}


echo get_data('https://www.google.com/', true); // Source code with lines
echo get_data('https://www.google.com/'); // Source code without lines
?>

希望它能让你上路。

于 2012-12-28T00:49:36.807 回答
1

您应该尝试在<pre></pre>标签之间打印结果;

echo '<pre>' . get_data($url) . '</pre>';
于 2012-12-27T22:50:05.850 回答
0

在 php 中使用htmlspecialchars()来打印源代码。

在您的代码中,使用

return htmlspecialchars($data);

代替

return $data;

于 2014-01-13T10:38:18.293 回答
0

添加标题 Content-Type: text/plain

header("Content-Type: plain/text"); 
于 2012-12-27T23:21:22.523 回答