簡體   English   中英

可以在file_get_content中設置php嗎?

[英]Can set php in file_get_content?

我想問一下能否根據用戶單擊的端口更改file_get_content()中的url嗎? 例如,如果用戶單擊port2將變為

$html = file_get_contents('http://..port2.html');

而如果用戶單擊端口3將變為

$html = file_get_contents('http://..port3.html');

我嘗試將鏈接設置為

$html = file_get_contents('http://..port<?=$mrtg_id?>.html');

但顯示錯誤。 有什么建議嗎?

你不可以做這個:

$html = file_get_contents('http://..port<?=$mrtg_id?>.html');

因為參數是用單引號引起來的字符串文字,並且php會將其解析為純文本,所以您要饋入file_get_contents()的正是這樣的:

http://..port<?=$mrtg_id?>.html

其次,您不想在字符串上下文中使用<?= <value> ?>因為這可用於從php中將變量作為字符串回顯。 它是<?php echo <value> ?>的簡寫版本,您正在嘗試有效地作為參數字符串值回顯的字符串中執行此操作。

因此,您需要利用雙引號,這允許php解析字符串中的變量:

$html = file_get_contents("http://..port{$mrtg_id}.html");

請參閱此處以獲取更多信息: http : //php.net/manual/en/language.types.string.php

您可以通過更多方式進行操作:

$html = file_get_contents("http://..port".$mrtg_id.".html");
$html = file_get_contents("http://..port{$mrtg_id}.html");
$html = file_get_contents("http://..port{$mrtg_id}.html");
$html = file_get_contents('http://..port'.$mrtg_id.'.html');

請注意,URL包含了不同的字符(“,”)

檢查手冊以獲取更多信息: http : //php.net/manual/en/language.types.string.php

您無需在此處放置PHP標記來分配值。 只需將其替換為以下變量即可;

$mrtg_id= '47071544';
$content = file_get_contents('http://..port'.$mrtg_id.'.html');

或者您可以使用heredoc

     $html = file_get_contents(trim(<<<FILE
http://..port{$mrtg_id}.html
FILE;
));

是的,這有點矯kill過正,並且您可能會遇到行尾的問題(我添加了trim() ),但是有人(我不會叫出來)在我有機會之前發布了所有簡單的文章。

哦,你也可以內爆

$html = file_get_contents(implode(['http://..port',$mrtg_id,'.html']));

您可以這樣:

$url = 'http://..port'.$mrtg_id.'.html';
$html = file_get_contents($url);

您嘗試的代碼:

$html = file_get_contents('http://..port<?=$mrtg_id?>.html');

不能將'之間的字符串解析為變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM