I would like to ask can i make the url in file_get_content() become changeable according to the port that user click? For example, if user click port2 will become
$html = file_get_contents('http://..port2.html');
while if user click port 3 will become
$html = file_get_contents('http://..port3.html');
i try to set the link as
$html = file_get_contents('http://..port<?=$mrtg_id?>.html');
but it shown error. Any suggestion?
You can do it in more ways:
$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');
Note the URL is enclosed with different characters (", ')
Check the manual for more informations: http://php.net/manual/en/language.types.string.php
You cannot do this:
$html = file_get_contents('http://..port<?=$mrtg_id?>.html');
because the parameter is a string literal in single quotes and php will parse it as plain text, so what you are feeding into file_get_contents()
is exactly this:
http://..port<?=$mrtg_id?>.html
Secondly, you do not want to use <?= <value> ?>
inside a string context because this serves to echo out a variable as a string from php. It is a shorthand version of <?php echo <value> ?>
, and you are trying to do this from within a string that is effectively being echoed out as the parameter string value.
So, what you need is to take advantage of double quotes, which allows php parsing of variables inside the string:
$html = file_get_contents("http://..port{$mrtg_id}.html");
See here for more information: http://php.net/manual/en/language.types.string.php
you do not need to put PHP tag to assign a value here. Just simply replace with variable as below;
$mrtg_id= '47071544';
$content = file_get_contents('http://..port'.$mrtg_id.'.html');
Or you can use heredoc
$html = file_get_contents(trim(<<<FILE
http://..port{$mrtg_id}.html
FILE;
));
Yes, its a bit overkill for this and you might have problems with line endings ( i added trim()
), but someone ( I wont call them out ) posted all the easy ones before I had a chance.
Oh, you could do it with implode too
$html = file_get_contents(implode(['http://..port',$mrtg_id,'.html']));
You can do like this:
$url = 'http://..port'.$mrtg_id.'.html';
$html = file_get_contents($url);
The code what you try:
$html = file_get_contents('http://..port<?=$mrtg_id?>.html');
the string between '
can't be parsered as a variable.