Is it possible to print html from an external page by replacing strings?

Tags: php
By : dcdeiv

I was wandering if it were possible to store a html schema page with special strings to replace with variable and how to do it.

In an external file, I would like to put the html structure of a product, let's call it schema.php:

<span id="{% id %}">{%= name %}</span>
<span>{%= imageURL() %}</span>

The example above is just a simpler example. In the external file, the html would be more complex. I know that if there were just few lines I could just echo them with a simple function but this is not the case.

In another file I have a class that handle products, let's call it class.php:

class Product {
    //logic that is useless to post here.

    public function imageURL() {
        return "/some/url".$this->id."jpg";

In this class I would like to add a function that take the content from schema.php and then echo it in the public file for users.

I tried with file_get_contents() and file_put_contents() but it just doesn't work:

$path_to_file = 'data/prodotti/';
$file_contents = file_get_contents($path_to_file);

$file_contents = str_replace(
  "{%= ",
  "<?php echo $this->",

$file_contents = str_replace(
  " }",
  "; ?>",

file_put_contents($path_to_file, $file_contents);

is it possible to call schema.php page and print it with custom variables?

By : dcdeiv


you can do it normaly with php require func. without any strings to replace, if you just want to use that file as "template" then:

in schema.php:

echo'<span id="'.$id.'">'.$name.'</span>

in class.php:

class Product {
//logic that is useless to post here.

public function imageURL() {
    return "/some/url".$this->id."jpg";
$imageURL = imageURL(); ?>

Index.php or whatever the main page that handles class.php and temp.php(schema)

//avoid undefined variables on errors
//in case that you don't check for values submitted
$id = 0;
$name = 0;
$imageURL = '';

//set vars values 
$id = /*something*/;
$name = /*something 2*/;
$imageURL = /*something3*/;
//all date will be replaced is ready, oky nothing to wait for

Note: If you gets these data from user, then you should validate with if(isset()).

hope that helps,

By : xYuri

By "schema page" I think you mean "template" and yes, but the best way to do it is to use an existing templating engine such as Smarty or a Mustache implementation like instead of implementing it yourself because of the risks of XSS, HTML-injection, and how you'll eventually want features like looping and conditionals.

By : Dai

If I am reading this correctly, Message would contain a List<MessageUser>.

If that's the case then this should get you close:

var List<Message> messages = 
    ( from m 
      in db.Messages 
          m.UserID == userid || m.MessageUsers.Any(mu => mu.UserID == userID) 
      select m).ToList();
By : Sam Axe

This video can help you solving your question :)
By: admin