【问题标题】:Accessing and printing HTML source code using PHP or JavaScript使用 PHP 或 JavaScript 访问和打印 HTML 源代码
【发布时间】:2012-12-13 06:50:14
【问题描述】:

我正在尝试访问并打印(或只是能够使用)任何使用 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.

【问题讨论】:

  • 你可以使用document.body.innerHTML,很简单,不是吗?
  • 您能进一步解释一下吗?也许举个例子? @gdoron

标签: javascript php html


【解决方案1】:

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

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

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

【讨论】:

  • 设置内容类型为纯文本?
  • +1 我不知道cURL 的远程连接速度比file_get_contents 快。
  • @SenorAmor 它打印出'Resource id #1',就是这样!
【解决方案2】:

你应该尝试在&lt;pre&gt;&lt;/pre&gt;标签之间打印结果;

echo '<pre>' . get_data($url) . '</pre>';

【讨论】:

  • 这似乎不起作用。它只是改变了显示网页的一些字体和格式。
  • 也许echo '&lt;pre&gt;'; print_r(get_data($url)); echo '&lt;pre&gt;';
【解决方案3】:

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

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

希望它能让你顺利上路。

【讨论】:

  • 非常感谢!这正是我所需要的。
【解决方案4】:

添加标题 Content-Type: text/plain

header("Content-Type: plain/text"); 

【讨论】:

    【解决方案5】:

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

    在您的代码中,使用

    return htmlspecialchars($data);

    而不是

    return $data;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 2011-12-13
      • 2021-10-09
      相关资源
      最近更新 更多