PHP DOM Creation vs echo HTML - php

I apologize in advance if this is deemed not constructive...
Which is better to do?
echo out html code
echo("<div>marry me natalie imbruglia... please</div>");
OR
$dom = new DOMDocument("1.0","utf-8");
element = $dom->createElement('test', 'This is the root element!');
$dom->appendChild($element);
echo $dom->saveXML();
I must also mention that the platform i'm using at work does not support this... please do not ask why, it is the way it is... i have to work within those bounds...

Personally, I would choose neither. Since I am used to Java Server Pages, I would rather use straight HTML/PHP interleaving like so ...
<?php $x
$x = "This is the root element!";
?>
<test><?= $x ?></test>
If I had to choose from one of the two options you provided, I would definitely go with the second one because it's much easier to modify the final XML structure in the future.
I'll just emphasize Darryl's comment in an earlier post - since I don't have the enough reputation right now to add a further comment underneath his. Maintenance which is often correlated to code readability is important. If you are asking this question because you are trying to squeeze out "performance" then you're looking in the wrong place.

Related

Add CDATA to XML element with SimpleXML and WITHOUT dom_import_simplexml()

I have a deadline for this project (Monday). It worked great on the localhost, but when I uploaded it to our web server, I discovered that we do not have all of the DOM package enabled and I cannot use the function dom_import_simplexml(). My server admin is ignoring my requests, probably because of the short notice, and I cannot possibly rewrite the XML system into a database system that quickly.
This appears to be the only error I'm encountering. Please, if you have any alternative ideas, I'd love to hear them. I'm at a loss, because I can't find any other solution. All I have to do is create some XML elements and populate them with CDATA values, and I can't believe that this is not supported by SimpleXML!
Please, are there any alternatives you can think of? I'm open, because I don't know what I can do.
// Add a <pages /> element
$xml->addChild('pages');
// Populate it with data
foreach($pages as $page){
$new = $xml->pages->addChild('page');
$new->addAttribute('pid', $page['pid']);
$new->addAttribute('title', $page['title']);
if(isset($page['ancestor']))
$new->addAttribute('ancestor', $page['ancestor']);
$node = dom_import_simplexml($new);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($page['content']));
}
Those last three lines obviously won't work, and I don't know what else I can do with them!
Thank you so much for any help you can provide.
them not supporting this is baffling. You must hack the stream.
$xml->node = '<![CDATA[character data]]>';
echo preg_replace('/\]\]></', ']]><', preg_replace('/<!\[CDATA/','<![CDATA', $xml->asXML()));
This is problematic, perhaps those strings might show up in your cdata somewhere. A risk you'll have to take.
Sorry I couldn't help you with your deadline, but at least anyone annoyed with using DOM or unable to use it will have a solution of sorts.

Direct HTML or PHP generated html

What is better / faster:
For example:
STATIC / direct HTML:
<?php
for($i=0;$i<$sth;$i++) {
?>
<tr>
<td>
<?php echo $content; ?>
</td>
</tr>
<?php
}
?>
OR
PHP generated HTML:
<?php
for($i=0;$i<$sth;$i++) {
echo "<tr><td>".$content."</td></tr>";
}
?>
Does it matter which option i choose?
Thanks
It's not so much a matter of speed which may vary based on use case, but of making the code clean and maintainable. Actually both examples make for code that's hard to maintain and read.
I'd suggest using a simple and lightweight templating engine to separate all logic from presentation.
I think that there is no substantial difference between the two, the question should be "Which one is more readable" IMHO and i think that using php and html inline is far less readable than echoing php. But that's just my idea.
The better: Generated html.
Generated html with php is far more easy to maintain and easier to read.
The faster: There is no significant speed difference. However on large dynamic websites where content is loaded from a database etc things might take a fraction of a second more time to output. However, the time you spend on updating a static html file is a lot more than editing dynamic content..
Go dynamic :]
In this case "PHP generated HTML" would be quicker because you are only doing one echo where as in "STATIC / direct HTML" you are doing $sth echos. If $sth is zero then "STATIC / direct HTML" would be quicker.
But seriously, the page is parsed and optimised/normalised so it doesn't make any difference. Parsing with less might be quicker because there are less context switches but this is the smallest part (compared to running it) so it makes negligible difference.
Just pick the style that you feel comfortable with.
Two codes represent the same thing, not differentiate in the speed , But the second code may be a little faster because the code does not contain more than one entry and exit signs.
<?php ?>
this will be carried out faster .
The first approach should be faster as it does not involve a lot of string concatenation. It's also better in terms of code readability.
I think the first solution:
It is clearer and do not require php elaborations with string to dispplay simple static content

PHP library for HTML output

Is there an standard output library that "knows" that php outputs to html?
For instance:
var_dump - this should be wrapped in <pre> or maybe in a table if the variable is an array
a version of echo that adds a "<br/>\n" in the end
Somewhere in the middle of PHPcode I want to add an H3 title:
.
?><h3><?= $title ?></h3><?
Out of php and then back in. I'd rather write:
tag_wrap($title, 'h3');
or
h3($title);
Obviously I can write a library myself, but I would prefer to use a conventional way if there is one.
Edit
3 Might not be a good example - I don't get much for using alternative syntax and I could have made it shorter.
1 and 2 are useful for debugging and quick testing.
I doubt that anyone would murder me for using some high-level html emitting functions of my own making when it saves a lot of writing.
In regards to #1, try xdebug's var_dump override, if you control your server and can install PHP extensions. The remote debugger and performance tools provided by xdebug are great additions to your arsenal. If you're looking only for pure PHP code, consider Kint or dBug to supplement var_dump.
In regards to #2 and #3, you don't need to do this. Rather, you probably shouldn't do this.
PHP makes a fine HTML templating language. Trying to create functions to emit HTML is going to lead you down a horrible road of basically implementing the DOM in a horribly awkward and backwards way. Considering how horribly awkward the DOM already is, that'll be quite an accomplishment. The future maintainers of your code are going to want to murder you for it.
There is no shame in escaping out of PHP to emit large blocks of HTML. Escaping out to emit a single tag, though, is completely silly. Don't do that, and don't create functions that do that. There are better ways.
First, don't forget that print and echo aren't functions, they're built in to the language parser. Because they're special snowflakes, they can take a list without parens. This can make some awkward HTML construction far less awkward. For example:
echo '<select name="', htmlspecialchars($select_name), '</select>';
foreach($list as $key => $value) {
echo '<option value="',
htmlspecialchars($key),
'">',
htmlspecialchars($value),
'</option>'
}
echo '</select>';
Next, PHP supports heredocs, a method of creating a double-quoted string without the double-quotes:
$snippet = <<<HERE
<h1>$heading</h1>
<p>
<span class="aside">$aside_content</span>
$actual_content
</p>
HERE;
With these two tools in your arsenal, you may find yourself breaking out of PHP far less frequently.
While there is a case for helper functions (there are only so many ways you can build a <select>, for example), you want to use these carefully and create them to reduce copy and paste, not simply to create them. The people that will be taking care of the code you're writing five years from now will appreciate you for it.
You should use a php template engine and just separate the entire presentation and logic. It make no sense for a educated programmer to try to create a library like that.

Performance difference between these methods

Is there any advantages/disadvantages to either of these statements over the other one:
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
echo "<p>Hello World</p>";
?>
OR
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
?>
<p>Hello World</p>
What i'm asking is, if i'm outputting a page using PHP should i keep closing the php tags and stick normal HTML in or echo out the HTML? Which is better?
if you want do be realy exact, there are three options:
the slowest:
echo "<p>Hello World</p>";
a bit faster (no need to check for inline-valiables because of single quotes):
echo '<p>Hello World</p>';
the fastest (no php-interpreting at all):
<p>Hello World</p>
but between all of this, the difference would be so minimalistic that you won't ever notice it - much more important: make your code redable and do it the same way everywhere, so nobody who's reading your code (and has to maintain it) gets confused. i personally would prefer the third method (so i can use code-completition in my IDE), but it's your choice - i know a lot of people who output everything using echo.
EDIT: to be complete, there are some more possibilitys i didn't mentioned like heredoc- and nowdoc-syntax, but this are basically the same as double/single-quotes... also, you could write print instead of echo and so on, but that wouldn't make a difference.
Method 2 is cleaner IMHO because you separate PHP code from HTML. Your IDE (if you use any) can parse your HTML tags and autocomplete them, and spot any typo's.
I'm not a PHP programmer but I would assume the 2nd method is faster, because PHP doesn't have to process the echo language construct, allocate buffer and all that stuff. It is also cleaner, and less of a hassle to modify the HTML.
Also, it would be wise to learn to use a template engine for your HTML in order to separate concerns. Smarty was popular a couple years ago, I don't know if it's still is.
Although the difference is negligible, you should stick normal outputing out of PHP tags. Echo command will have to be parsed by PHP interpreter and then sent as output.
The only difference is that with echo(); you instruct PHP to process the code, otherwise, there is no difference at all.
One way or another, the result is exactly the same and for performance, there is almost no differences at all. Like... How much time PHP needs to process that echo();? I think with miliseconds you could run in problems calculating numbers that small. Hehe.

php code to return xml

hi there i have a question and need help on this from you guys .
I have a database created for a game called gamesleaderboard and the fields are id, player_name, score, leveltime. and my task is after getting the score, i have to insert it to a database and sort the dbase accordingly.
after sorting, the code will return an xml in the following structure:
Ahmad100080
Basel95090
Samer920100
Seyd900110
Ahmad100080
Basel95090
Samer920100
Seyd900110
Ahmad100080
Basel95090
plz tell me the necessary details how to do this thankyou.
In most simplistic terms there is nothing really special to do here, you can output XML in exactly the same way you would output HTML in PHP, this is a simple example
You can also use the DOMDocument class (or SimpleXML) to output XML, this is a bit more complex but is better practice. For an example of creating XML with DOMDocument using data from MySQL read more here
Don't forget to send the correct Content-Type header before outputting the XML document tho.
If you are very new to XML I would highly recommend SimpleXML as it will be enough for most of needs. Creating XML using "echo" and strings is not only a dangeous but also a very bad programming technique.
Using SimpleXML you can easily add new nodes, adding child nodes and attributes to them. If you can getting started reading the PHP docs, just search for a SimpleXML tutorial on google. Or ask your questions right here.
$query=mysql_query("Select * from gamesleaderboard ");
$number=mysql_num_rows($query);
if ($query==0)
{
echo "0 rows Affected";
}
$doc= new DOMDocument();
$doc->formatOutput=true;
$root= $doc->createElement("Games");
$doc->appendChild($root);
for ($i=0; $i<$number; $i++){
$row=mysql_fetch_array($qex);
$node=$doc->createElement("user");
$pn=$doc->createElement("player_name");
$pn->appendChild($doc->createTextNode($row["player_name"]));
$node->appendChild($pn);
$sc=$doc->createElement("score");
$sc->appendChild($doc->createTextNode($row["score"]));
$node->appendChild($sc);
$root->appendChild($node);
}
echo $doc->saveXML();
This will display the answer exactly you want. I just tested it. I was probably in highschool when you asked this question here. Anyway it'll help someone else.

Categories