如何使用 HTML DOM 将所有相对 URL 转换为绝对 URL?

How can you put all relative URL to absolute URL using HTML DOM?

我需要仅使用 HTML DOM 将网页的所有相对 URL 替换为绝对 URL。这是可能的?

我也在用yii2

例子

站点:http://www.example.com

<link href="/css/site.css" rel="stylesheet">
<a href="/page">Page</a>

结果:

<link href="http://www.example.com/css/site.css" rel="stylesheet">
<a href="http://www.example.com/page">Page</a>

你可以使用 url 助手

假设您 css 在 /yii2/web/css

<?php 
   use  yii\helpers\Url;
 echo '<link href="' .Url::base() . '/css/site.css' .'" rel="stylesheet">';

假设您 css 在 /yii2/css

echo '<link href="' .Url::base() . '../css/site.css' .'" rel="stylesheet">';

将 $scheme 参数设置为 true 以 return 一个绝对 url 如果你想 link 一个控制器动作。

Url::to(['my_controller/action'], true);

http://www.yiiframework.com/doc-2.0/yii-helpers-baseurl.html#to()-detail

对于文件,您可以使用此 Html::a( $text, $url = null, $options = [] ) 和以下选项

// A normal string. This will use the exact string as the href attribute
$url = 'images/logo.png'; // This returns href='images/logo.png'

// A string starting with a Yii2 alias
$url = '@web/images/logo.png' // This returns href='http://www.example.com/images/logo.png'