Question

OK, so you all know PHP can parse .php documents, containing HTML code, with embedded PHP code. And I believe Ruby (Erb) allows pretty much the same thing.

But, how does it do it? (Trust me I've had good look into the sources, but spotting something like this in 1mil. lines of code is not the easiest thing).

What I thought is :

  • What matters is what is being echoed
  • The initial PHP/HTML text is converted to a valid PHP script
  • PHP code, as indicated by <?php and ?> starting/ending points, remains as-is
  • The rest is converted using echo statements.

E.g. :

<html>
     <head>
           <title><?php echo "This is the title"; ?></title>
     </head>
     <body>
     </body>
</html>

Converted to :

echo "<html>";
echo "<head>";
echo "<title>";
echo "This is the title";
echo "</title>";
echo "</head>";
echo "<body>";
echo "</body>";
echo "</html>";

Would that make sense?


P.S. If you're wondering about the very nature of the question, I'm currently building something like for a language of my own. And it works rather fine, though I'm experiencing some conversion speed issues for longer input documents, so I though of exploring my alternatives... :-)

Was it helpful?

Solution

I may get down voted because I don't have any references, but...

What you're referring to is how every referential IT system works. It takes data from a dynamic resource (either external or on-page) & appends it into the page

I want to call it parsing but I don't think that's the right technical term. My thinking is in PHP, your page will first go through PHP (where it will output any PHP elements as plain text), and then that parsed document will be sent to the front-end HTML processor

So to answer your question, I would say that you're probably over-complicating it. HTML is the base-standard for output, so why re-invent the wheel? Your parser should only look for its relevant tags & then run the code inside. It doesn't have to recognize the HTML inside - just treat it all as plain text, unless you want to render more of your code

If what you proposed was right, we wouldn't have to write any HTML in Rails or PHP. We'd just use the in-built methods

For example:

<p><? echo "hello" ?></p>

In my simplistic definition, PHP would first render the "plain text" output for the <? ?>, and then send the formatted page to the front-end as HTML

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top