【问题标题】:Why PHP echo in `background-image:ulr()` always get an escape character?为什么`background-image:url()`中的PHP回显总是得到一个转义字符?
【发布时间】:2018-05-01 14:23:37
【问题描述】:

我的代码总是有这个问题:

<?php
  $imgurl = "https://cdn.jsdelivr.net/example.png";
  $get_style = 'background-image: url(\''.$imgurl.'\'); ';
?>
<figure id="centerbg" class="centerbg" style="<?php echo $get_style; ?>background-position: center center;background-attachment: inherit;">

但无论我做什么,html 总是显示:

<figure id="centerbg" class="centerbg" style="background-image: url(&quot;https://cdn.jsdelivr.net/example.png&quot;); background-position: center center; background-attachment: inherit;">

我也试过了:

<figure id="centerbg" class="centerbg" style="background-image: url(<?php echo $imgurl ?>);background-position: center center;background-attachment: inherit;">

但是一点用处都没有!

谁能帮帮我? TAT

感谢您的帮助,但似乎我和您的代码在这个单个文件中都可以正常工作:https://api.mashiro.top/cover/test.php,但总是在我的生产站点中获得转义字符(与封面图像相同的 HTML id):https://2heng.xin/ ,真的很奇怪,而且我的网站中的其他部分是否有可能出错?

我不知道为什么style="background-image: url(&amp;quot;https://cdn.jsdelivr.net/example.jpg&amp;quot;);" 可以在我的浏览器(Chrome 和 Firefox)中显示图像,但这不是一个好的表达方式呃?

【问题讨论】:

  • @Marko Paju 还是不行...而且我的 PHP 文件在 ANSI...

标签: php html wordpress


【解决方案1】:

您也可以只删除 $get_style 变量上的单引号。

<?php
  $imgurl = "https://cdn.jsdelivr.net/example.png";
  $get_style = 'background-image: url('.$imgurl.');';
?>
<figure id="centerbg" class="centerbg" style="<?php echo $get_style; ?>background-position: center center;background-attachment: inherit;height:100%;">

您的网站似乎正在使用 WordPress,所以 link 也可能对您有所帮助。

【讨论】:

    【解决方案2】:

    对于这种情况,您可以混合使用 double-quotessingle-quotes

    <?php
      $imgurl = "https://cdn.jsdelivr.net/example.png";
      $get_style = "background-image: url('".$imgurl."'); "; 
    ?>
    <figure id="centerbg" class="centerbg" style="<?php echo $get_style; ?>background-position: center center;background-attachment: inherit;">
    

    【讨论】:

    • 我真的不明白为什么,和你一样的代码,在这个单一的 php 文件中工作正常:api.mashiro.top/cover/test.php 但在我的网站中获得了转义字符(相同的 html 标签 id,封面实际图片):2heng.xin
    【解决方案3】:

    只有我们这个。

    <?php 
       $imgurl = "https://cdn.jsdelivr.net/example.png";
       $get_style = "background-image: url('".$imgurl."');";
    ?>
    

    如果您仍然遇到同样的问题,也可以查看http://php.net/manual/en/function.htmlspecialchars-decode.php

    【讨论】:

    • 我真的不明白为什么,和你一样的代码,在这个单一的 php 文件中工作正常:api.mashiro.top/cover/test.php 但在我的网站中获得了转义字符(相同的 html 标记 id,封面实际图片):2heng.xinLAL
    【解决方案4】:

    试试这个 - 我经常使用这种方法,没有问题。

    <?php $imgurl = 'https://cdn.jsdelivr.net/example.png'; ?>
    
    <figure id="centerbg" class="centerbg" style="background-image: url('<?php echo $imgurl; ?>'); background-position: center center; background-attachment: inherit;">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-07
      • 2021-12-19
      • 2020-07-07
      • 1970-01-01
      • 2018-07-16
      • 2013-04-05
      • 2013-12-16
      • 2021-11-27
      相关资源
      最近更新 更多