php file_get_contents不输出svg

cdmah0mi  于 5个月前  发布在  PHP
关注(0)|答案(7)|浏览(75)

我试图用php抓取一个svg文件并将其输出到页面上。网站是建立在WordPress上的。

<?php 
    echo file_get_contents("site.com/wp-content/themes/oaklandcentral/img/fb_logo.svg"); 
?>

字符串
什么都没有显示。实际的链接是正确的,直接进入svg。有什么想法吗?

zd287kbt

zd287kbt1#

第一个月
假设条件:

  • 您的“文件名”字符串以协议开头,例如“http://”

您可以直接从浏览器访问文件(即不是文件/文件夹权限问题);
file_get_contents返回的是E?(E_contents告诉你什么了吗?)
我不希望看到一些服务器没有配置为允许file_get_contents(或readfile与URL),所以我会检查调查这第一(也许allow_url_fopenin php.ini?).
如果不是这种情况(或者是主机提供商的限制),并且您无法找到问题的原因,那么CURL * 应该 * 工作(在大多数服务器上!)。

$url = 'http://example.com/path-to/fb_logo.svg';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
$svg = curl_exec($ch);
curl_close($ch);

echo $svg;

字符串

编辑:

1.你也可以使用php includeif you remove the xml header tag from your SVG file
1.我假设您希望显示SVG图像而不是它的文本代码,在这种情况下,为什么不像其他图像那样简单地显示<img src="<?php echo $mySvgFileUrl"; ?>">呢?

wlwcrazw

wlwcrazw2#

在回显svg之前使用:header("Content-Type: image/svg+xml");添加header。有时浏览器默认接收的数据是html。

6yoyoihd

6yoyoihd3#

有什么问题。
1.文件不在你想的地方。
1.文件权限不允许代码读取文件。
尝试调试:

<?php 
    $file = "site.com/wp-content/themes/oaklandcentral/img/fb_logo.svg";
    if ( file_exists($file) ) {
        echo file_get_contents($file); 
    } else {
        echo "File $file does not exist";
    }
?>

字符串
尝试使用curl获取页面。查看头部和原始https响应。

curl -v URL_TO_PAGE

nwlqm0z1

nwlqm0z14#

尝试:
第一个月
这似乎对我有用,而使用get_template_directory_uri()则不行(它抛出了一个OpenSSL错误)
然后,您可以将SVG作为目标并按您的意愿设置样式。例如:

<button class="btn btn-primary">
  <?php echo file_get_contents(get_template_directory().'/theme/img/chevron-right-solid.svg'); ?>
</button>

字符串
CSS可能是:
.btn svg { line-height: 1.2; max-height: 1rem;}

xuo3flqw

xuo3flqw5#

这段PHP代码应该可以工作:

$svgfilename = 'fb_logo.svg';
$svgcontent = false;        
$svgcontent = file_get_contents(get_template_directory() . '/wp-content/themes/oaklandcentral/img/' . $svgfilename));
//We can str_replace some values here such as width="32", height="32", viewBox="0 0 32 32", etc.
print '<a title="'.trim(basename($svgfilename)).'" href="'.get_template_directory() . '/wp-content/themes/oaklandcentral/img/' . $svgfilename.'" >'.$svgcontent.'</a>';

字符串

mlnl4t2r

mlnl4t2r6#

尝试使用下面的代码。
$opts = array(
'http'=>array(
'method'=>“GET”,
'header'=>“Accept-language:en\r\n”。
“Cookie:foo=bar\r\n”

);
$context = stream_context_create($opts);
$file = file_get_contents('site.com/wp-content/themes/oaklandcentral/img/fb_logo.svg',false,$context);

z31licg0

z31licg07#

路径错误,请使用file_get_contents( get_template_directory() . '/img/fb_logo.svg' )

相关问题