skip to Main Content

I have a php app where I have snippets of code that I want to process and store in a variable. It might be the output of array data with HTML that I want stored…

$myVar = { // bracket represents starting the store

  foreach ($myarray as $key => $value) {
    echo ‘<td>’ . $value . ‘</td>’;
  }
}// close bracket represents end store

Now the variable would hold the value of what that full echo output would be.

Is there a php function, process, or recommend way of doing this.

I don’t have a framework I’m using on this project.

I am looking for a solution because I don’t know the right approach.

2

Answers


  1. You can use the ob_start and ob_get_clean functions to store the output of the code in a variable:

        ob_start();
        foreach ($myarray as $key => $value) {
          echo ‘<td>’ . $value . ‘</td>’;
        }
        $myVar = ob_get_clean();
    

    ob_start turns on output buffering, which captures all output from your script and stores it in a buffer. The ob_get_clean function then retrieves the contents of the buffer and discards it, leaving you with the contents stored in the $myVar variable.

    Login or Signup to reply.
  2. How about:

    $myVar = '<td>' . implode('</td><td>', $myArray) . '</td>';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search