OttherCreek
OttherCreek

Reputation: 993

How to add a <svg> Element to an existing <svg>Tag via PHP?

I have a <svg>-Tag and want to add some <circle> elements to it dynamically.

This is the <svg>-Tag:

<svg xmlns="..." version="1.1"
    width="400" height="600" viewBox="0 0 400 600">
      
    <image xlink:href="<?=$map->ImagePath?>" x="0"y="0"height="100%"/>
    
    <?php echo $this->calcCircles(); ?>

</svg>

This ist the PHP function in which the circles are generated

public function calcCircles(){
  $circles='';
  foreach(...){
          ... 
         $circles.='<circle cx="'.$xValue.'" cy="'.$differenceY.'" r="10" fill="#..." .../>';
  }
  return $circles;
}

Are there any ideas on how to do that?

Upvotes: 0

Views: 222

Answers (1)

IncredibleHat
IncredibleHat

Reputation: 4104

Since calcCircles is an object method, then doing <?php $calcCircles?> would be wrong.

You would instead do <?php echo $yourObject->calcCircles();?> and return the $circles inside that method with return $circles;:

<svg xmlns="..." version="1.1"
    width="400" height="600" viewBox="0 0 400 600">
      
    <image xlink:href="<?=$map->ImagePath?>" x="0"y="0"height="100%"/>
    
    <?php echo $yourObject->calcCircles(); ?>

</svg>
public function calcCircles(){
    $circles = '';
    foreach(...){
        ... 
        $circles .= '<circle cx="'.$xValue.'" cy="'.$differenceY.'" r="10" fill="#..." .../>';
    }
    return $circles; // return the value
}

Note in this example it is unknown the object name because you did not provide that. Use what you have setup. If the svg generation is inside the SAME object as calcCircles() then use $this->calcCircles().

Upvotes: 1

Related Questions