John Davidson

css - How can I insert the contents of an SVG file into clipPath with PHP?

0 comments
Message:


To make my code more DRY, I would like to be able to use an existing SVG file for a clipPath. For example:


picture-frame.svg:


<svg width="2000" height="1000" viewBox="0 0 2000 1000" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M932.66 998.369L932.251 ..." fill="black"/>
</svg>

example.php:


...
<body>

<svg viewBox="0 0 2000 1000" xmlns="https://www.w3.org/2000/svg" version="1.1" style="position: absolute; left: -9999px; overflow: hidden;">
<defs>
<clipPath id="my-clip">
<?php echo insertSVG( 'picture-frame' ); ?>
</clipPath>
</defs>
</svg>

<div style="clip-path: url('#my-clip');">
<img />
</div>

</body>
...

The code to insert the SVG code is simple using file_get_contents(), see this blog post.


The tricky part is <clipPath> doesn't allow <svg> as a descendent, so copying the file contents verbatim does not work. Nor does using SimpleXMLElement to change <svg> to a tag with no-effect, like <g>.


How can I can insert just the contents of the root <svg> element (ie. <path> in my example above) into the clipPath element?



My Answer:
One way to achieve this is to use DOMDocument to parse the SVG file and extract the contents of the element. Here's an example of how you can modify your insertSVG function to achieve this:

php
function insertSVG($filename) {
$svg = file_get_contents($filename . '.svg');

$dom = new DOMDocument();
$dom->loadXML($svg);

$xpath = new DOMXPath($dom);

// Get the contents of the element
$svgContents = '';
foreach ($xpath->query('//svg/*') as $node) {
$svgContents .= $dom->saveXML($node);
}

return $svgContents;
}


With this modified function, you can now insert just the contents of the element into the element in your example.php file:

php
...















...


This way, you can reuse the contents of the SVG file within the element without any issues.

Rate this post

3 of 5 based on 8917 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us