DOM class injection in PHP - php

idea
Via jQuery, I was able to mark all :first-child and :last-child elements in document (well, almost all :)) with class first which could I later style (i.e. first li in ul#navigation would be easily adressable as ul#navigation .first).
I used following code:
var $f = $('*:first-child')
$f.addClass('first');
var $l = $('body *:last-child')
$l.addClass('last');
example
http://jsbin.com/ikuca/3
Example is already here - it's not the way to do it however, it's just an idea prototyped in other, for me at the moment easier language.
question
Now, my question is if it's possible to do the same via php, so non-JS users/gadgets could have the same effects and additional styling and also it would be less overkill on browser.
So, is it possible to capture output, parse it as html and inject this class easily in php?
clarification
I'm quite aware of output buffering, just haven't done much stuff with it - also, i'm not sure about modificating output string in php as parsed dom (without regex) - and how tough on server it'll be - with caching of course, so this whole stuff will run once until the page will be edited again.

I'm sure you could use output buffering to capture your assembled PHP page and then use DOM and XPath on it to add the class attributes, but the question is, why don't you just put the classes onto the elements when assembling the page in the first place? Saves you the jQuery and the capturing.
Also, adding the CSS classes with jQuery to be able to do ul#navigation.first is somewhat odd too, because the jQuery expression you used is a CSS selector, so you could use it directly to style the first child from your CSS file. The only reason to add a class .first is if you want to be backwards compatible with browsers unable to process :first-child.

I think you'll find it's easier to do this in jQuery than PHP, but it can be done in PHP.
To capture output you want output buffering, which you activate with the ob_start function, before sending any output. You can pass ob_start() a PHP function which will receive the HTML code as a parameter and can then manipulate the HTML using PHP's DOM functions.

jQuery runs in the client's borwser. PHP runs on the server. You can't modify the DOM in the browser from the server once it is served.
What you could do, is to serve the page already with the proper classes. For example in PHP when you print a table:
<table>
<?php
$i=0;
foreach ($rows as $row):
?>
<tr class=<?php echo ($i%2==0?'even':'odd')?>
<td><?php echo $row;</td>
</tr>
<?php
endforeach;
?>
</table>
ps. Do you really want to support clients without JS?

You could even use the same CSS selectors by using some of the libraries mentioned here.
I read that the phpQuery library even has the same :first-child pseudo-class you need.
I sincerely hope you plan on using caching or else your CPU usage will go up 100% with a few request.

Related

is this a good practice to output html using php? [duplicate]

I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using PHP and HTML. Is it better to have the whole document in PHP and echo HTML like so:
<?php
doSomething();
echo "<div id=\"some_div\">Content</div>";
?>
Or have a HTML file like so and just add in the PHP:
<html>
<body>
<?php doSomething(); ?>
<div id="some_div">Content</div>
</body>
</html>
It seems tidier to echo HTML, especially if lots of PHP gets used throughout the page, but doing so loses all formatting of the HTML i.e. colors in the IDE etc.
There are varying opinions on this. I think there are two good ways:
Use a templating engine like Smarty that completely separates code and presentation.
Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:
<?php $content = doSomething();
// complex calculations
?>
<html>
<body>
<?php echo $content; ?>
<div id="some_div">Content</div>
</body>
</html>
Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.
I think this would depend on your group's or your own decided convention. And it can and should vary depending on what type of file you're working in. If you follow the MVC pattern then your views should be the latter. If you're writing a class or some non-output script/code then you should use the former.
Try to keep a separation of display or formatting of output and the logic that provides the data. For instance let's say you need to make a quick page that runs a simple query and outputs some data. In this case (where there is no other existing infrastructure or framework) you could place the logic in an include or in the top or the bottom of the file. Example:
<?php
# define some functions here that provide data in a raw format
?>
<html>
<body>
<?php foreach($foo = data_function($some_parameter) as $key => $value): ?>
<p>
<?=$value;?>
</p>
<?php endforeach; ?>
</body>
</html>
Or you could place the logic and function definitions in an include file or at the bottom of the file.
Now if you're producing some sort of class that has output (it really shouldn't) then you would echo the HTML or return it from the method being called. Preferably return it so that it can be output whenever and however the implementer would like.
The syntax highlighting is an important benefit of the second method, as you said. But also, if you're following good practices where logic and presentation are separated, you will naturally find that your files that contain HTML are almost entirely HTML, which then, naturally, leads to your second method again. This is the standard for MVC frameworks and the like. You'll have a bunch of files that are all PHP, doing logic, and then when that's done they'll include a presentation file which is mostly HTML with a sprinkling of PHP.
Simple:
More PHP - close HTML in PHP. When you generate HTML code in PHP, when you are doing something like a class, so it is better to make it in echo.
Less PHP - close PHP in HTML. This is stuff like just putting vars into fields of HTML stuff, like forms... And such.
The best approach is to separate the HTML from the PHP using template system or at least some kind of HTML skeleton like:
<main>
<header/>
<top-nav/>
<left-col>
<body />
</left-col>
<right-col />
<footer/>
</main>
Each node represents a template file e.g. main.php, hrader.php and so on. Than you have to separate the PHP code from the templates as something like functions.php and fineally use your second approach for template files and keeping functions clean of "echos" and HTML.
If you can, use a template engine instead.
Although it is slightly easier at first to mix your HTML and PHP, separating them makes things much easier to maintain later on.
I would recommend checking out TemplateLite which is based on Smarty but is a little more light weight.
I've reached a conclusion that using views in MVC framework e.g. Laravel, Yii, CodeIgniter is the best approach even if you are not displaying the html straight away.
Inside the view do all the echoing and looping of prepared variables, don't create or call functions there, unless formatting existing data e.g. date to specific format date('Y-m-d', strtodate(123456789)). It should be used only for creating HTML, not processing it. That's what frameworks have controllers for.
If using plain PHP, create you own view function to pass 3 variables to - html file, array of variables, and if you want to get output as string or print it straight away for the browser. I don't find a need for it as using frameworks is pretty much a standard. (I might improve the answer in the future by creating the function to get view generated HTML) Please see added edit below as a sample.
Frameworks allow you to get the HTML of the view instead of displaying it. So if you need to generate separate tables or other elements, pass the variables to a view, and return HTML.
Different fremeworks may use various type of templating languages e.g. blade. They help formatting the data, and essentially make templates easier to work with. It's also not necessary to use them for displaying data, or if forced to use it by the framework, just do required processing before posting the variables, and just "print" it using something like {{ yourVariable }} or {{ yourVariable.someProperty }}
Edit: here's a plain PHP (not framework PHP) - simple-php-view repository as a sample view library that allows to generate HTML using variables. Could be suitable for school/university projects or such where frameworks may not be allowed.
The repository allows to generate HTML at any time by calling a function and passing required variables to it, similar to frameworks. Separately generated HTML can then be combined by another view.
It depends on the context. If you are outputting a lot of HTML with attributes, you're going to get sick of escaping the quotation marks in PHP strings. However, there is no need to use ?><p><? instead of echo "<p>"; either. It's really just a matter of personal taste.
The second method is what I usually use. And it was the default method for me too. It is just to handy to get php to work inside html rather than echo out the html code. But I had to modify the httpd.conf file as my server just commented out the php code.

PHP library to create inlined CSS from files or from <style> tags?

I would like a library to create inlined CSS+HTML from .html and .css files or from an HTML file with tags in the head. I would prefer a PHP library if possible.
By inlined CSS I mean something like
<span style="font: bla bla bla">Hi There!</span>
versus
<style>
.greeting { font: bla bla bla; }
</style>
I often need to put HTML into emails and this would simplify the process greatly.
If anyone is interested, my current solution (for stuff that isn't restyled often) is to use the Smarty templating engine to create the document, and to assign the style="" part to a variable inside the template.
Then I can use that variable in each tag (like <td {$td_style}> (FYI - {$variable} is how smarty variables are inserted into a template) and have it generate the appropriate email-friendly HTML.
However I want something that is more general, and for which I can just feed it some HTML and CSS rather than have to convert all of it to a smarty template.
Does anyone know if a library like this exists?
Although I don't know of a library that handles this, if you're set on PHP, you could do this fairly easily I would think by using CSSTidy to parse the CSS, and then using an XML parser (ideal if your code is well-formed--maybe SimpleXML or the DOM extension) or one of the PHP-based HTML parsers I see out there to parse the HTML, so you can alter the HTML via DOM methods according to CSS rules.
If you don't need it tied into a PHP process though, I recommend going with JavaScript for almost anything like this, since it can work in the client-side (and in different environments) and be a handy tool for anyone wishing to do this; you should be able to parse the CSS using http://glazman.org/JSCSSP/ and then using DOMParser() and the IE equivalent as needed (for XHTML) or use innerHTML, this htmlparser, or any other HTML Parsers.
Btw, I know <style> works in emails since my add-on Color Source injects them to get syntax highlighting in emails, though I guess you were only saying it is more complicated for you to do it that way.

Combine jQuery and Zen-Coding php ports to emulate client side programming style on server side scripts

When I write client side code, I use HTML/CSS/JavaScript and lately jQuery to both speed up coding, and use improved methods to achieve the same goal.
In my text editor I use zen-coding to speed up the writing of code, and also to avoid errors. I was looking at zen-coding as a jQuery plugin for a while, but it has a fatal flaw, that you want the HTML to be written and sent to the client plain before any javascript kicks in.
Although we can use JavaScript servers (env.js or node.js) and therefore do a lot of development server side using JavaScript and jQuery, I am not comfortable moving over yet as it is an emerging technology, and has many differences and drawbacks (and also some major advantages).
I want to continue using PHP server side, but develop in the way I am most comfortable with, and familiar with which is client side JavaScript.
Therefore - I have been looking into QueryPath which is a PHP port of jQuery that aims to take the best and most relevant parts of jQuery and re-work it to suit the server environment.
That is all great, and I have now been looking at two PHP classes capable of parsing zen-coding which when combined acts as a great templating engine and also avoids errors in my code.
The problem I am having is that neither zen-coding parsers support anywhere near a full set of zen-coding features.
So finally my questions (sorry for the rather lengthy intro)
Is there a better server side zen-coding parser I can use in my PHP code?
Is there a good (very concise and full featured) alternative templating system to using zen-coding? (which I know is not originally designed for this task)
Is there a better approach I should take to achieve my ultimate goal of narrowing the divide between the way I code client side and server side?
Is there a PHP library that implements a load of utility functions that by using will enhance the security/performance of my code without me learning all the internal workings? (like jQuery does for javascript)
NB: I am looking more for functional equivalence than syntactic similarity - although both are a plus for me.
Here is some commented test code that should illuminate what I am trying to achieve:
<?php
// first php based zen-coding parser
// http://code.google.com/p/zen-php
require_once 'ZenPHP/ZenPHP.php';
// my own wrapper function
function zp($abbr){ return ZenPHP::expand($abbr); }
// second php based zen-coding parser
// https://github.com/philipwalton/PW_Zen_Coder
require_once 'PW_Zen_Coder/PW_Zen_Coder.php';
$zc = new PW_Zen_Coder;
// my own wrapper function
function pwzc($abbr){ global $zc; return $zc->expand($abbr); }
// php port of jQuery with a new server-side flavor
// http://querypath.org/
require_once 'QueryPath/QueryPath.php';
// initialize query path with simple html document structure
qp(zp('html>head+body'))
// add a heading and paragraph to the body
->find('body')
->html(zp('h1{Zen Coding and jQuery - Server Side}+p{This has all been implemented as a php port of JavaScript libraries}'))
// add a comments link to the paragraph
->find('p')
->append(pwzc('span.comments>a[href=mailto:this#comment.com]{send a comment}'))
// decide to use some jquery - so add it to the head
->find(':root head')
->append(zp('script[type=text/javascript][src=/jquery.js]'))
// add an alert script to announce use of jQuery
->find(':root body')
->append(zp('script[type=text/javascript]{$(function(){ alert("just decided to use some jQuery") })}'))
// send it to the browser!
->writeHTML();
/* This will output the following html
<html>
<head>
<script type="text/javascript" src="/jquery.js"></script>
</head>
<body>
<h1>
Zen Coding and jQuery - Server Side
</h1>
<p>
This has all been implemented as a php port of JavaScript libraries
<span class="comments">
<a href="mailto:this#comment.com">
send a comment
</a>
</span>
</p>
<script type="text/javascript">
$(function(){ alert("just decided to use some jQuery") })
</script>
</body>
</html>
*/
?>
Any help is much appreciated
Questions 1 and 2
A template engine sort of like the ZenCoding example would be Haml. The syntax is different, but it's similarily short and quite concise in general.
If you like using ZenCoding, you could consider simply using an editor with support for it. PhpStorm for example bundles a ZenCoding plugin by default. I'm sure others (such as Vim) have plugins for this purpose as well. However, this approach will only allow you to write it: Once you've written it, the editor will expand it to the actual HTML markup.
Question 3
I think a part of this problem is that they are inherently completely different things. The client-side scripting side of things, it's typically a user-interface only. Certain programming styles and approaches are used with the browser UI. However, on the server-side, you generally have data processing, and for data processing, other types of patterns work better.
I'm a bit doubtful whether the QueryPath thinger you're using is a particularily good choice... It seems to somewhat obscure the HTML markup itself, making it harder to see what the exact result of the operations would be.
For generation of HTML markup on the server-side, I would recommend using a template engine or simply using PHP-only templates.
One approach you could use is to completely throw away server-side markup generation. Of course this is not a good idea for everything, but for complex web apps (in style of Gmail or such), you can generate the entire markup using just JavaScript. On the server, you would only use JSON to return data. This way you don't have to deal with markup on the server and can keep using jQuery or whatever on the client for the entire thing.
Question 4
Again I'm a bit doubtful about this whole thing. If you don't understand what's going on under the hood, how can you produce good code? How can you understand or debug things correctly when they go wrong or don't work as expected?
Now I don't know if you're a PHP guru or not, but personally I would suggest that you learn how things work. You don't have to write everything from scratch to do that though. Choosing a framework is a good idea, and it will do exactly what you ask: It will do many things for you, so you don't have to worry as much about security or other things.
Personally I would recommend using the Zend Framework, since it provides a wide range of components, and you can only use the parts you want - you don't have to use the whole framework at once. However, it can be a bit complex at first especially if you're not very familiar with PHP and OOP concepts, so you might have better luck initially going with some other framework.
first of all i want to say i have up-voted your answer because it is well explained and have some nice point to consider; then i want let you think about theese other point:
GOTCHAS
IMHO you are overcomplicating the whole thing ;)
between the entire PHP code needed to generate the HTML and the outputted HTML itself there is very very low difference in term of lenght of writed-code.
the code is completely unredeable for everyone who don't know the 3 libs or whatever it is.
the speed of site-load will decrease enourmously compared to the semplicity of the vanilla HTML.
what the real difference between:
h1{Zen Coding and jQuery - Server Side}+p{This has all been implemented as a php port of JavaScript libraries}
and
<h1>Zen Coding and jQuery - Server Side</h1><p>This has all been implemented as a php port of JavaScript libraries</p>
6.. as you know both zen-coding and queryPath are not intended to be used the way you are doing, at least not in a production scenario.
7.. The fact that jQuery have a good documentation and it's usefull to use doesn't mean that can be used successfully from anyone. ( the mere copy/past is not considered a coding skill IMO )
SOLUTION
it is probably the best solution for you looking at some kind of PHP Templating Engine like smarty, this will suit your needs in various way:
security/performance
narrowing the divide between the way I code client side and server side
an example would be: ( to be considered a very primitive example, smarty have more powerfull functionalities )
<!-- index.tpl -->
<html>
<head> {$scriptLink}
</head>
<body> <h1> {$h1Text} </h1>
<p> {$pText}
<span class="comments">
{$aText}
</span>
</p> {$scriptFunc}
</body>
</html>
// index.php
require('Smarty.class.php');
$smarty = new Smarty;
$smarty->assign("scriptLink", "<script type=\"text/javascript\" src=\"/jquery.js\"></script>");
$smarty->assign("scriptFunc", "<script type=\"text/javascript\">$(function(){ alert(\"hello world\") });</script>");
$smarty->assign("h1Text", "Zen Coding and jQuery - Server Side");
$smarty->assign("pText", "This has all been implemented as a php port of JavaScript libraries");
$smarty->assign("aText", "send a comment");
$smarty->assign("aLink", "mailto:this#comment.com|mailCheck");
$smarty->display('index.tpl');
NOTE: the use of mailCheck, yes you should also consider eventuality some kind of variable check. smarty can do it....
hope this help. ;)
I'm not sure to understand your question, but I usually have this simple approach:
<?php
ob_start();
$config->js[] = 'js/jquery.js';
?>
<h1>
<del>Zen Coding and jQuery - Server Side</del>
<ins>HTML and PHP :-)</ins>
</h1>
<p>
This has all been implemented <del>as a php port of JavaScript libraries</del>
<ins>in php</ins>
<span class="comments">
<a href="mailto:this#comment.com">
send a comment
</a>
</span>
</p>
<script type="text/javascript">
$(function(){ alert("just decided to use some jQuery") })
</script>
<?php $content = ob_get_clean() ?>
<?php require 'layout.php' ?>
Some points:
ob_start turn on the output buffer (the output is not sent to the client but stored in an internal buffer)
$config->js[] = 'js/jquery.js'; will say to the layout to add a new script tag
Then there is the plain HTML that have to be decorated with the layout
<?php $content = ob_get_clean() ?> get the output stored in the internal buffer and assign it to a variable.
<?php require 'layout.php' ?> will include the layout with the main HTML structure and some logic to print metas, title, <link> tags, <script> tags, and so on... The layout will contain a <?php echo $content ?> to print the page content.
The point 1, 4 and 5 can be delegated to a Front Controller, so the view can be just:
<?php
$config->js[] = 'js/jquery.js';
?>
<h1>
<del>Zen Coding and jQuery - Server Side</del>
<ins>HTML and PHP :-)</ins>
</h1>
<p>
This has all been implemented <del>as a php port of JavaScript libraries</del>
<ins>in php</ins>
<span class="comments">
<a href="mailto:this#comment.com">
send a comment
</a>
</span>
</p>
<script type="text/javascript">
$(function(){ alert("just decided to use some jQuery") })
</script>
I think that you are entirely missing the point of ZenCoding. ZenCoding is meant to be integrated in your editor, not in your application. It's a way of quickly writing HTML using fewer keystrokes and with fewer errors. Your commented test code doesn't look all that usable to me. I prefer the plain HTML version.
If speed and quality of writing plain HTML is an issue for you, perhaps it's time to switch to a better editor? One with support for ZenCoding, auto-balancing HTML tags, autocompletion, snippets/templates, etcetera? I have configured Vim to do all this for me. I've been told StormPHP is also quite good.
I'm considerably biased in my answer, as I am the author of QueryPath, but I like what you are trying to do. (It's always thrilling to see my code used in a way I never anticipated.)
QueryPath has an extension mechanism. Using it, you can add methods directly to QueryPath. So you could, for example, write a simple plugin that would let you replace qp()->find()->append(zp()) with something like qp()->zp($selector, $zencode);.
You can take a look at the extensions in QueryPath/Extensions and see how they work. (QPXML.php is an easy one to grok.)
If you do end up building (and releasing) a solution, please let me know.

What is the best practice to use when using PHP and HTML?

I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using PHP and HTML. Is it better to have the whole document in PHP and echo HTML like so:
<?php
doSomething();
echo "<div id=\"some_div\">Content</div>";
?>
Or have a HTML file like so and just add in the PHP:
<html>
<body>
<?php doSomething(); ?>
<div id="some_div">Content</div>
</body>
</html>
It seems tidier to echo HTML, especially if lots of PHP gets used throughout the page, but doing so loses all formatting of the HTML i.e. colors in the IDE etc.
There are varying opinions on this. I think there are two good ways:
Use a templating engine like Smarty that completely separates code and presentation.
Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:
<?php $content = doSomething();
// complex calculations
?>
<html>
<body>
<?php echo $content; ?>
<div id="some_div">Content</div>
</body>
</html>
Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.
I think this would depend on your group's or your own decided convention. And it can and should vary depending on what type of file you're working in. If you follow the MVC pattern then your views should be the latter. If you're writing a class or some non-output script/code then you should use the former.
Try to keep a separation of display or formatting of output and the logic that provides the data. For instance let's say you need to make a quick page that runs a simple query and outputs some data. In this case (where there is no other existing infrastructure or framework) you could place the logic in an include or in the top or the bottom of the file. Example:
<?php
# define some functions here that provide data in a raw format
?>
<html>
<body>
<?php foreach($foo = data_function($some_parameter) as $key => $value): ?>
<p>
<?=$value;?>
</p>
<?php endforeach; ?>
</body>
</html>
Or you could place the logic and function definitions in an include file or at the bottom of the file.
Now if you're producing some sort of class that has output (it really shouldn't) then you would echo the HTML or return it from the method being called. Preferably return it so that it can be output whenever and however the implementer would like.
The syntax highlighting is an important benefit of the second method, as you said. But also, if you're following good practices where logic and presentation are separated, you will naturally find that your files that contain HTML are almost entirely HTML, which then, naturally, leads to your second method again. This is the standard for MVC frameworks and the like. You'll have a bunch of files that are all PHP, doing logic, and then when that's done they'll include a presentation file which is mostly HTML with a sprinkling of PHP.
Simple:
More PHP - close HTML in PHP. When you generate HTML code in PHP, when you are doing something like a class, so it is better to make it in echo.
Less PHP - close PHP in HTML. This is stuff like just putting vars into fields of HTML stuff, like forms... And such.
The best approach is to separate the HTML from the PHP using template system or at least some kind of HTML skeleton like:
<main>
<header/>
<top-nav/>
<left-col>
<body />
</left-col>
<right-col />
<footer/>
</main>
Each node represents a template file e.g. main.php, hrader.php and so on. Than you have to separate the PHP code from the templates as something like functions.php and fineally use your second approach for template files and keeping functions clean of "echos" and HTML.
If you can, use a template engine instead.
Although it is slightly easier at first to mix your HTML and PHP, separating them makes things much easier to maintain later on.
I would recommend checking out TemplateLite which is based on Smarty but is a little more light weight.
I've reached a conclusion that using views in MVC framework e.g. Laravel, Yii, CodeIgniter is the best approach even if you are not displaying the html straight away.
Inside the view do all the echoing and looping of prepared variables, don't create or call functions there, unless formatting existing data e.g. date to specific format date('Y-m-d', strtodate(123456789)). It should be used only for creating HTML, not processing it. That's what frameworks have controllers for.
If using plain PHP, create you own view function to pass 3 variables to - html file, array of variables, and if you want to get output as string or print it straight away for the browser. I don't find a need for it as using frameworks is pretty much a standard. (I might improve the answer in the future by creating the function to get view generated HTML) Please see added edit below as a sample.
Frameworks allow you to get the HTML of the view instead of displaying it. So if you need to generate separate tables or other elements, pass the variables to a view, and return HTML.
Different fremeworks may use various type of templating languages e.g. blade. They help formatting the data, and essentially make templates easier to work with. It's also not necessary to use them for displaying data, or if forced to use it by the framework, just do required processing before posting the variables, and just "print" it using something like {{ yourVariable }} or {{ yourVariable.someProperty }}
Edit: here's a plain PHP (not framework PHP) - simple-php-view repository as a sample view library that allows to generate HTML using variables. Could be suitable for school/university projects or such where frameworks may not be allowed.
The repository allows to generate HTML at any time by calling a function and passing required variables to it, similar to frameworks. Separately generated HTML can then be combined by another view.
It depends on the context. If you are outputting a lot of HTML with attributes, you're going to get sick of escaping the quotation marks in PHP strings. However, there is no need to use ?><p><? instead of echo "<p>"; either. It's really just a matter of personal taste.
The second method is what I usually use. And it was the default method for me too. It is just to handy to get php to work inside html rather than echo out the html code. But I had to modify the httpd.conf file as my server just commented out the php code.

PHP echoing HTML code with more PHP included

I have blocks of HTML code in a MySQL database and my framework needs to print these within a PHP template which will be outputted to the browser. To do so I make this call:
</tr>
<!-- Section 3 -->
<?php echo SIN_SiteView::get('section3') ?>
<tr>
Which gets the code either from the APC or MySQL, now the code it obtains looks like this:
<td height="280" colspan="2" bgcolor="#00abd2">
<a href="#">
<img src="<?php echo SIN_Utilities::l("image", "home_flash.png")?>" width="710" height="280" border="0" />
</a>
As you can see I need to run all images through a method known as "l" which I use to easily change images paths. Now the issue is if I echo that block of code it will simply be echoed as a string and not work.
I tried surrounding the php with '. [code] .' and removing the php but that also did not work. Does anyone have any ideas on how I could properly echo this to the page.
Thanks.
UPDATE: I think I need to be using the eval() command thanks to some of the comments, I simply do not understand how to implement it in my situation. Any simple examples would be greatly appreciated, for example how do I change this line:
<?php echo SIN_SiteView::get('section3') ?>
To echo the entire block featured above, thanks again.
I think you want eval rather than echo. See this slightly different question.
My solution would be to eval '?>'.$myhtml.'<?php'.
Is the marketing team adding the php code to the html you are storing?
If not, maybe you could change your <?php echo FUNCTION() ?> into #FUNCTION() and evolve your SIN_SiteView::get() into your own templating interpreter?
I agree with cHao though; it would probably be easier to adopt one of the templating packages out there and convert your data over.
You'll need to use eval to evaluate the inline PHP. However, this is potentially quite risky (eval is evil, etc.), especially if any of the content that's being fetched is user sourced.
e.g.: At the very least, what's the stop the user inlining...
<?php die(); ?>
...within the content they enter.
As such, you'll need to take a great deal of care, if there's really no alternative to this approach.
Some updates:
If you're new to PHP I'd recommend having a re-think. Chances are there's no need to use eval. (Unless there's a dynamically customised content on a per-user basis then you don't need it.) What are you trying to achieve?
What specific error/problem are you having? (I presume you're using var_dump or print_r for debug purposes, etc.) As the content you need to eval isn't pure PHP (it's HTML with PHP in) you'll need to embed the PHP close and (re-)open tags as #Borealid illustrated.

Categories