在php中,如何将图像的相对路径替换为绝对路径,并将该php文件下载为文档文件


In php how to replace relative path to absolute path for images and download that php file as a doc file?

我的网站:www.test.com/abc/test

Php文件:content.Php

<!-- content starts here -->
<h2>Welcome test page</h2>
<p>This is test page.</p>
<p><img src="/abc/test/img.jpg" /></p>
<!-- content ends here -->

我有执行文件并下载为文档文件的功能。我使用"includeonce()"方法来执行PHP文件,也使用适当的头将该文件下载为文档文件。

除了图像,一切似乎都很好。因为我使用"相对路径"来引用图像。文档文件在绝对路径下运行良好,但它没有加载相对路径的图像。

问题:我不想将content.php文件替换为图像的"绝对路径"。使用任何PHP预定义函数,是否有一种方法可以读取文件并替换"相对到绝对"路径,然后下载文件而不修改源文件?

您可以使用html <base>(在head部分内)标记并为图像设置"root"。

例如:

<head>
..
<base href="http://yourdomain.com/optional_base_folder_to_all_images/" />
..
</head>

也许你可以用file_get_contents将源代码放入一个变量中,然后,你可以用str_replace 替换所有的图像路径

例如:

$source_code = file_get_contents(path/to/file.php);
$new_source = str_replace('<img src="/', '<img src="http://www.test.com/abc/test/', $source_code);