【问题标题】:cURL get_data($url) with absolute URL带有绝对 URL 的 cURL get_data($url)
【发布时间】:2012-01-12 08:06:30
【问题描述】:

我正在使用此代码通过 cURL 获取数据

$url='http://example.com/'; //URL to get content from..
print_r(get_data($url)); //Dumps the content

/* Gets the data from a URL */
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;
}

但是,此代码返回具有相对 url 的数据。如何使用此相对 url 并使用绝对 url 打印?可能与 preg_replace.. 但如何?

【问题讨论】:

  • 您的意思是要将返回数据中的链接从相对转换为绝对?

标签: php curl


【解决方案1】:

查看 HTML base 标记。如果您想让浏览器进行所有相对到绝对的转换,您应该会发现它很有帮助:

$data = get_data($url);
// Note: ideally you should use DOM manipulation to inject the <base>
// tag inside the <head> section
$data = str_replace("<head>", "<head><base href=\"$url\">", $data);
echo $data;

【讨论】:

  • 太棒了!正是我想要的。
  • 这会在我的站点中返回“标头已发送”错误。我该怎么办?
  • +1 表示使用经常被忽视的标签的良好、简单的解决方案。
【解决方案2】:

我认为你必须使用像http://simplehtmldom.sourceforge.net/这样的HTML解析器,并将所有链接替换为正确的路径。

【讨论】:

    猜你喜欢
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    相关资源
    最近更新 更多