php - 使用 PHP 的 file_get_contents 后将类添加到 SVG 元素

标签 php html svg

我需要获取 SVG 图像并将图像插入页面。我正在使用以下方法获取图像:

<?php echo file_get_contents("logo.svg"); ?>

输出类似

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"">
    <path d="M12 2c5.514 0 10 4.486"></path>
</svg>

插入到页面后如何向 SVG 元素添加类?如:

<svg class="LogoStyle" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"">
    <path d="M12 2c5.514 0 10 4.486"></path>
</svg>

或定位到路径元素:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"">
    <path class="LogoStyle" d="M12 2c5.514 0 10 4.486"></path>
</svg>

任何帮助都会很好,谢谢!

最佳答案

您可以将 svg 存储为 PHP 变量,然后使用 DOMDocument() 功能来完成此操作。

$svg = file_get_contents("logo.svg");
$dom = new DOMDocument();
$dom->loadHTML($svg);
foreach($dom->getElementsByTagName('svg') as $element) {
    $element->setAttribute('class','new-classname-goes-here');  
}
$dom->saveHTML();
$svg = $dom->saveHTML();    
echo $svg;

要定位 path 而不是 svg 元素,只需将 getElementsByTagName('svg') 更新为 getElementsByTagName('路径')

关于php - 使用 PHP 的 file_get_contents 后将类添加到 SVG 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35376462/

相关文章:

javascript - 更改导航项的颜色(下拉 - 单击)

python - 将 svg 保存到临时文件 Python

javascript - 使用D3.js找到SVG路径的质心

javascript - 在将字符串传递给 javascript 之前正确转义 php 中的字符串

javascript - 每个应用程序应该只有一个 EventSource 对象吗?

php - slider 中图像之间的空白空间

javascript - 长文本的省略号

php - Client-Server-Communication with php and android

php - Codeigniter、timezone_menu 和 date_default_timezone_set

php - Android:UTF-8 编码的 HttpPost JSON 字符串到 PHP