简体   繁体   中英

PHP - Printing variables stored as a string

I've written the entire website in HTML and PHP but I ran into a small problem. After almost completing the website I was told to put all content in the database rather than just HTML. As I'm doing that I noticed that text with inline PHP variables doesn't get read when taken from the database.

Original Code:

<div>Hello <?php echo $World; ?></div>

New Code:

<div><?php getContent("title"); ?></div>

I have tried two ways of storing them in the database:
First method, text saved: Hello <?php echo $World; ?> Hello <?php echo $World; ?>
Which prints out Hello and ignores the variable.

Second method, text saved: Hello $World
Which prints out Hello $World instead of the value of $World

Other things I've tried:
Hello $$World - Hello $$World
Hello {$World} - Hello {$World}

Read about sprintf

echo sprintf("Hello %s",$World);

and store that "Hello %s" in the database and use $World like before.

If you implement it in the right way, you can make your website show in different languages.

But i thing you should more get into templating in php and/or use a template engine for php.

http://php.net/manual/de/function.sprintf.php

https://de.wikipedia.org/wiki/Template-Engine#Template-Engines_f.C3.BCr_PHP

And after the note in the comment:

The are many!! ways in php to do this Hello <?php echo $World; ?> Hello <?php echo $World; ?> But in the end you only store real data in the database. No php code or html just plain data. One of them can be templates like Hello %s other dynamic data like user names or whatever. And a template engine can help you to do that all in a proper way. (an templates are file-based, mostly) Keep that in mind.

You can use placeholders in your text, then use str_replace to put replace the placeholders with your variables.

DB String:

<div>Hello WORLD_VAR</div>

And in the code:

$text = str_replace('WORLD_VAR', $World, $text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM