1

When I try run this command on my SVG file, the browser says no data has been received and I get an error in my Apache log file.

preg_match("/(<g(\s|\S)*?<\/g>)/i", $SVG, $Matches);

My SVG file is here.

And the actual error that I'm getting is this

[core:notice] [pid 20852] AH00052: child pid 31338 exit signal Segmentation fault (11)

What have I done wrong here and how do I fix this?

Brian Leishman
  • 8,155
  • 11
  • 57
  • 93
  • You can't be serious with the close vote? I'm using the `preg_replace` function and getting an error that I don't know how to resolve in the context that I'm receiving the error in. In what possible way is that not a programming question? – Brian Leishman May 15 '15 at 21:29
  • Does the regex work if you test it on your local machine? Can your provide the content of `$SVG` (Googles asking for permissions to view it)? – chris85 May 15 '15 at 21:36
  • Try to strip down the SVG to the bare minimum when it still fails. – Ondřej Hlaváček May 15 '15 at 22:00
  • 2
    svg is xml, I don't know why you obtain a segment fault, but the good approach is to use an xml parser, for example DOMDocument or the combo XMLReader/XMLWriter, but not `preg_replace` – Casimir et Hippolyte May 15 '15 at 22:07

1 Answers1

1

Use the PHP DOM functions to parse XML files. There is a good reason, why you shouldn't use RegEX to parse XML :-)

Since you are looking for all <g ...></g> tags, you can do this like this:

$xdoc = new DOMDocument;
// load your .svg
$xdoc->Load('0057b8.svg');
// get all "g"-tags
$gTags = $xdoc->getElementsByTagName('g');
// since the return is a DOMNodeList, we loop through all (even if it's only 1)
foreach($gTags as $gTag) {
    // and here we can e.g. get the attributes
    echo $gTag->getAttribute('transform') . PHP_EOL;
    echo $gTag->getAttribute('fill') . PHP_EOL;
    echo $gTag->getAttribute('stroke') . PHP_EOL;
    // or set a new attribute
    $gTag->setAttribute('stroke-width', '5');
}

The g-tags will be DOMElements, so you can read in the reference to get all possible methods on them.

Community
  • 1
  • 1
Marc
  • 3,683
  • 8
  • 34
  • 48
  • Yes! This was the sort of exact thing I was looking for, I know the woes of parsing XML/HTML with regex but I couldn't seem to find another way to do it, but this worked perfectly. Thanks! – Brian Leishman May 18 '15 at 13:29