2017-11-02 09:17



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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duanmei1946 duanmei1946 4年前

    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:

    点赞 评论 复制链接分享
  • dqd72925 dqd72925 4年前

    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.

    点赞 评论 复制链接分享
  • dongzhuoxie1244 dongzhuoxie1244 4年前

    Or you can use heredoc

         $html = file_get_contents(trim(<<<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']));
    点赞 评论 复制链接分享
  • dowdw44426 dowdw44426 4年前

    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');
    点赞 评论 复制链接分享
  • dongnaoxia0927 dongnaoxia0927 4年前

    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:


    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:

    点赞 评论 复制链接分享