Php parse html template

Simple PHP Template Parsing

I want to create a simple PHP Class for parsing basic HTML email templates in PHP. Very basic. Pass a PHP array into a function which has a variable containing the Email template HTML with placeholders <> . The PHP Array’s Key will be the variable name in the template and it;s Value will be the desired output when the email HTML is sent as an email. I thought it might be useful for me to create a simple PHP Class that could do this same thing and speed things up by being flexible. So here is some basic example HTML for the Email body. Variables that will need to be replaced in the template with values from PHP variables are wrapped with <>

  

Account Details

Thank you for registering on our site, your account details are as follows:
Username: >
Password: >

In the above example there are 2 variables that need to be populated. <> and > I would like to be able to simply pass my Class function a PHP Array where the Array key is the variable name and the value is the value that would be populated in my email template. So something like this would be passed into my method/function that parses the email template.

$emailValues = array( 'username' => 'My username value here', 'password' => 'My password value here' ); $emailHtml = new EmailParser($emailValues); echo $emailHtml; 
  

Account Details

Thank you for registering on our site, your account details are as follows:
Username: My username value here
Password: My password value here

I am curious how I could best achieve this? My main question would be how to pass in the PHP Array and have it map out to a variable name to do the replacements. The PHP Array Key would be the Variable name in the template.

Читайте также:  Готовое выпадающее меню css

Источник

Simple PHP Template Parsing

Question: I’m trying to write a very basic template engine for a project and ended up taking the approach described in this article, which write template variables like and to simply use to parse the templates and put in the variable values. The resulting code was this: Using the following extract: I am able to create an array of elements: What I would actually like to do, though, is to retrieve all text nodes but to allow certain HTML tags to be ‘looked over’ .

Simple PHP Template Parsing

I want to create a simple PHP Class for parsing basic HTML email templates in PHP. Very basic. Pass a PHP Array into a function which has a variable containing the Email template HTML with placeholders > . The PHP Array’s Key will be the variable name in the template and it;s Value will be the desired output when the email HTML is sent as an email.

I thought it might be useful for me to create a simple PHP Class that could do this same thing and speed things up by being flexible.

So here is some basic example HTML for the Email body. Variables that will need to be replaced in the template with values from PHP variables are wrapped with >

  

Account Details

Thank you for registering on our site, your account details are as follows:
Username: >
Password: >

In the above example there are 2 variables that need to be populated. > and >

I would like to be able to simply pass my Class function a PHP array where the Array key is the variable name and the value is the value that would be populated in my email template.

So something like this would be passed into my method/function that parses the email template.

$emailValues = array( 'username' => 'My username value here', 'password' => 'My password value here' ); $emailHtml = new EmailParser($emailValues); echo $emailHtml; 
  

Account Details

Thank you for registering on our site, your account details are as follows:
Username: My username value here
Password: My password value here

I am curious how I could best achieve this? My main question would be how to pass in the PHP Array and have it map out to a variable name to do the replacements. The PHP Array Key would be the Variable name in the template.

It should just be a case of looping through the values and using str_replace on them.

 'My username value here', 'password' => 'My password value here' ); $emailHtml = new EmailParser($emailValues); echo $emailHtml->output(); class EmailParser < protected $_openingTag = '>'; protected $_emailValues; protected $_emailHtml =  

Account Details

Thank you for registering on our site, your account details are as follows:
Username: >
Password: >

HTML; public function __construct($emailValues) < $this->_emailValues = $emailValues; > public function output() < $html = $this->_emailHtml; foreach ($this->_emailValues as $key => $value) < $html = str_replace($this->_openingTag . $key . $this->_closingTag, $value, $html); > return $html; > >

these two functions should help :

function template($string,$hash) < foreach ( $hash as $ind=>$val ) < $string = str_replace('>',$val,$string); > $string = preg_replace('/\\>/is','',$string); return $string; > function template_file($file,$hash) < $string = file_get_contents($file); if ($string) < $string = template($string,$hash); >return $string; > 
 if( file_exists( $sTemplateName ) ) < $sHtml = file_get_contents( $sTemplateName ); for( $i = 0; $i < $iCountData; ++$i ) < $sHtml = str_ireplace( $aPlaceholders[ $i ], $aData[ $i ], $sHtml ); >$sReplacedHtml = $sHtml; > > > catch( Exception $oException ) < // Log if desired. >return $sReplacedHtml; > > $aPlaceholders = array( '>', '>' ); $aData = array( 'Why so pro', 'dontchangeme' ); $oParser = new ParseTemplate; $sReplacedHtml = $oParser->Email( 'intemplate.html', $aPlaceholders, $aData ); file_put_contents( 'outtemplate.html', $sReplacedHtml ); ?> 

I already use a function for this kind of purpose.

// file class.bo3.php, more about this class here: https://github.com/One-Shift/BO3-BOzon/blob/master/backoffice/class/class.bo3.php class bo3 < public static function c2r ($args = [], $target) < foreach ($args as $index =>$value) < $target = str_replace("", $value, $target); > return $target; > > 
$emailValues = [' username' => 'My username value here', // in the template the code need to be "" 'password' => 'My password value here' // in the template the code need to be "" ]; $template = file_get_contents("path/to/html/file") $finishedTemplate = bo3::c2r($emailValues, $template); 

If you want to change the code format from to > , just change it in the class function c2r().

PHP parse_str() Function, The parse_str () function parses a query string into variables. Note: If the array parameter is not set, variables set by this function will overwrite existing …

PHP DOM — Parse text nodes that contain certain HTML tags

I recently received help in parsing all text nodes from an HTML document. The resulting code was this:

$doc = new DOMDocument(); $doc->loadHTML($contents); $doc->loadHTML("

not in the brackets..

"); $xpath = new DOMXPath($doc); $textnodes = $xpath->evaluate('//text()');

Using the following extract:

This is a nested HTML tag.

I am able to create an array of elements:

Array ( [0] => This is a [1] => nested [2] => HTML [3] => tag [4] => . ) 

What I would actually like to do, though, is to retrieve all text nodes but to allow certain HTML tags to be ‘looked over’ . For instance, I do not want , and tags to be parsed as individual nodes; I would rather they are joined on to the previous text node. The above array would, ideally, look like this:

Array ( [0] => This is a nested HTML tag. ) 

On the other hand, the

tags should be recognised as separate nodes. So the following text:

paragraph 1 here

paragraph 2

Would ideally be parsed as:

Array ( [0] => paragraph 1 here [1] => paragraph 2 

I have done some reading about XPath and the PHP DOM, but honestly, I don’t really have a clue how to go about this. Can anybody point me in the right direction? Thank you.

Just to clarify the output must be in array format; my aim is to parse all text from a page so it can then be used in a translation file. Certain HTML tags ( , etc) are therefore desirable in the parsed text in order to keep full sentences together — and to keep the markup roughly intact — in the new translation file.

Consider using ****_tags on the ‘looked over tags’ and using the second parameter of the allowable tags on the ones you want to actually split by.

If you have a node and want to normalize it as plain text:

XPATH: 'string(thenode)' DOM: $thenode->textContent; 

This will ignore all child nodes which are not text nodes and return it as a single string.

So in your example, an xpath like string(//p) will get you an array of plain text paragraphs with all elements removed. You could do the same thing with the DOM using getElementsByTagName() and fetching textContent property for each result.

If you have requirements more complex than this you might be better off using XSL with an identity transform to generate a new DOM tree that’s more to your liking. For example, if you have some top-level nodes you want (like

), and want to **** out some but not all of its subnodes (e.g., «keep em and strong , but collapse cite upward), then a DOM solution will be quite tedious.

Parse html string in php Code Example, $dom = new DOMDocument(); $dom->loadHTMLFile(‘path/to/htmlfile.html’); // or loadHTML($str) $dom->load(‘path/to/xmlfile.xml’); // or loadXML($str) $table = …

How to parse basic template logic in PHP?

I’m trying to write a very basic template engine for a project and ended up taking the approach described in this article, which write template variables like [@variable] and to simply use str_replace() to parse the templates and put in the variable values.

This is really simply and seems to work well, but despite my best efforts there are situations in which basic logic is really needed in the template itself. I don’t need anything complicated, just a way to have single if/else or ternary statements. For example, something like [if@something?»text»:»other text»] .

What might be a good approach to parsing basic logic in templates, like shown in the above example?

I’m working on an AJAX heavy website, so I have a PHP AJAX controller that receives requests and then returns a JSON encoded response. Here’s an example:

. else if($req == 'getContent') < $template = new Template('template.tpl'); $template->setData(array( 'date' => time(), 'var' => 'foo', 'foo' => 'bar' )); $response = array( 'error' => null, 'content' => template->getOutput() ); > . echo json_encode($response); 
lots and lots and lots of HTML . variables [@date] mixed in [@foo] somewhere with HTML [@bar] . lots and lots and lots of HTML 

If I wasn’t using a template engine (which just uses str_replace() to put the variable values into the template after getting it with file_get_contents() ), then I would have to do this:

. else if($req == 'getContent') < $output = ' lots and lots and lots of HTML' . time() . ' . variables ' . $foo . ' mixed in ' . $bar . 'somewhere with HTML . lots and lots and lots of HTML '; $response = array( 'error' =>null, 'content' => $output ); > . echo json_encode($response); 

The whole point of what I’m trying to accomplish here is to separate huge blocks of HTML text (in some cases, literally entire page bodies) from my AJAX handler and instead keep them in separate files, which is far more readable and keeps the AJAX handler from becoming ridiculously massive.

PHP is already a templating language . For example, this is what your example above would look like in PHP:

Think twice before adding another layer of complexity on top of this.

There are templating libraries like Smarty and they have their justification, for example caching, or when you want to separate code and design in a safe way (i.e. give designers something they can modify without breaking code). If it’s just for your own use, though, then using native PHP is a very strong option.

The reason is to avoid mixing HTML with PHP and having spaghetti code

There is nothing wrong with using simple PHP inside your HTML code. (and whether you have spaghetti code in PHP or your new templating language doesn’t really make a difference. )

What’s bad (and leading to Spaghetti code) is mixing huge chunks of code with the HTML output, for example calculations or preparations. Those should always be separate from the HTML.

The PHP inside the HTML structure should do only simple comparisons, if/then/else checks, for / foreach loops, and any operations directly related to outputting data (e.g. htmlspecialchars or simple calculations).

If you stick to that, you can happily use native PHP for your templating needs.

Maybe you can define another template definition for functions, like:

[*function_name][param1,param2,param3] 

For example for your example:

[*defined][@something,"text","other"] 

And in your template engine code you can write the logic for the » defined» template function .

PHP parse_str — Parses the string into variables Code, All Languages >> PHP >> WordPress >> PHP parse_str — Parses the string into variables “PHP parse_str — Parses the string into variables” Code Answer. PHP …

Источник

Оцените статью