PHP解析html并更改链接

时间:2013-01-28 12:40:53

标签: php html

我正在使用PHP创建代理服务器,我想知道是否可以将链接(相对和绝对)转换为绝对URL,然后更改链接以便它们转到我网站上的某个位置。很难解释,但这基本上就是我想要的

<html>
<body>
 <a href='http://www.google.com'>This is a link</a><br><br>
 <a href='/index.php'>This is another</a><br>
 <form action='/act.php'>
   <input type='submit'>
 </form>

我将使用

file_get_contents("http://www.thiswebsite.com")

预期输出为

     <html>
<body>
 <a href='proxy.php?url=http://www.google.com'>This is a link</a><br><br>
 <a href='proxy.php?url=http://www.thiswebsite.com/index.php'>This is another</a><br>
 <form action='proxy.php?url=http://www.thiswebsite.com/act.php'>
   <input type='submit'>
 </form>

由于

1 个答案:

答案 0 :(得分:3)

您可以尝试使用PHP DOMDocument API。你会写一些类似的东西:

<?php
$document = file_get_contents("http://www.thiswebsite.com");
$doc = new DOMDocument();
$doc->loadHTML($document);

$xpath = new DOMXpath($doc);
$anchors = $xpath->query("//a[@href]");
foreach( $anchors as $anchor) {
    $href = $anchor->getAttribute("href");
    $your_site_prefix = "proxy.php?url=";
    $anchor->setAttribute("href", $your_site_prefix . $href);
}

echo $xpath->document->saveHTML();
?>
相关问题