PHP 从 SVG 文件中获取 svg 标签,并在 DIV 中以 HTML 显示

标签 php svg domdocument

我想读取一个 SVG 文件并从该文件中获取 SVG 标签(因为我想在 html 中显示 svg,例如 <div><svg>...</svg></div> 而没有 xml header )。

并在浏览器中像 HTML 一样显示这个 svg 标签——像 SVG 图像一样打印这个 SVG 标签。因为现在我得到了错误的输出“DOMNodeList Object ( [length] => 1 )”。

PHP

$doc = new DOMDocument();
$doc->load('http://example.com/logo.svg');
$svg = $doc->getElementsByTagName('svg');

echo "<div style='width: 100%, height: 100%; '>";
print_r($svg); // DOMNodeList Object ( [length] => 1 ) 
echo "</div>";

最佳答案

我找到了解决方案,但这并不是我的问题的确切答案。所以我不会将其标记为答案,但我将此解决方案留在这里。也许会有人需要它...:)

我只是读取文件内容,然后寻找字符串"的位置,然后减去这段代码。

PHP

<?php 
$svg_file = file_get_contents('http://example.com/logo.svg');

$find_string   = '<svg';
$position = strpos($svg_file, $find_string);

$svg_file_new = substr($svg_file, $position);

echo "<div style='width:100%; height:100%;' >" . $svg_file_new . "</div>";

?>

关于PHP 从 SVG 文件中获取 svg 标签,并在 DIV 中以 HTML 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29991284/

相关文章:

php - 在我的站点中使用 PHPBB2 登录凭据

php - "Read More"按钮在 PHP、MySQL CMS 中停止工作

php - 如果使用 PHP 登录,则更改整个站点

javascript - 如何在 React Native 中渲染 svg 图像?

php - 使用 DomDocument 将实体添加到 DOCTYPE

javascript - `document.write` 在此 js 片段中起什么作用?

php - 如何从 DOMDocument 中获取所有子节点?

javascript - 在 joomla 模块中使用 var 和 php 的 js 对象

javascript - 将图像更改为内联 SVG >> 以获得所有 SVG 功能

javascript - 尝试使用链接来创建换行文本