Using twig extensions in Drupal 7 I would like to be able to use some custom PHP code that generates an SVG image in my .tpl.twig file. Since I can't write PHP in a twig template I figured I should try and make a twig extension (http://symfony.com/doc/current/cookbook/templating/twig_extension.html)

How could this be done in Drupal? Or is there another way?
When you are using tfd7 you can use extensions, functions, etc. The easiest way to go is to create an own module for handling all the php-functions.

In your OWN_MODULE.module:

function OWN_MODULE_twig_function() {
  $functions = [];
  $functions['XYZ_unset_key'] = new TwigSimpleFunction('XYZ_unset_key', 'XYZ_unset_key_callable');

  ...

  return $functions;
}

function XYZ_unset_key_callable($key, $array) {
  unset($array[$key];
  return $array;
}


After that you can use the function XYZ_unset_key in your twig-files:

&lt;div&gt;
  {{ XYZ_unset_key('field_xyz', 'content') }}
&lt;/div&gt;