Search code examples
phpcode-snippets

How can I keep an HTML snippet in a separate file, plug variables in as needed, and echo it out on demand?


For instance, let's say I have a snippet of code, which I'd like to keep separate. for now, we'll call it snippet.php.

snippet.php would be a simple block of reusable HTML which would have php variables in it. Something like this:

<article>
    <h1>{$headline}</h1>
    <p>${$body}</p>
</article>

I'd like to be able to return this code from a function, along the lines of this:

function writeArticle($headline, $body){
    return "contents of snippet.php using the variables passed in to the function"
}

I know I could just use html in a string to return, but the actual snippet would be fairly complex, and I want it to be modular.


Solution

  • One method is using file_get_contents and str_replace

    HTML:

    <article>
         <h1>[-HEADLINE-]</h1>
         <p>[-BODY-]</p>
    </article>
    

    PHP:

    function writeArticle($headline,$body){
          $content = file_get_contents("[add your html directory here]/file.html",true);
          $content = str_replace("[-HEADLINE-]",$headline,$content);
          $content = str_replace("[-BODY-]",$body,$content);
    
          echo $content;
     }