UPDATE:
I know I can use <ol> directky in the output but I remember using something like:
<?php echo $i++; ?> when I worked on a wordpress blog once. Every time I inserted that tag a number greater than the previous appeared so I basically did:
<?php echo $i++; ?> Text
<?php echo $i++; ?> Text
<?php echo $i++; ?> Text
I'm a front end guy (HTML/CSS) so please excuse this basic question. I just need to know what code in PHP I can use to number some text.
Text
Text
Text
into:
Text
Text
Text
Kind of like what <ol> does in html but in PHP.
Updated answer:
You can use a variable as you already do (the example you are posting should already work). Just initialize it using $i = 0;
Old answer:
You have a fundamental misunderstanding here. PHP is a scripting language, not a markup language. PHP does operations like connecting to data sources, calculating, making additions, changing entries in databases, and so on. PHP code, in short, is a series of commands that are executed. PHP has no design elements, tags and formatting options in itself.
PHP can (and usually does) output HTML (Where you have <ol>) to display things.
You can have an array of arbitrary data in PHP, coming from a file or data source:
$array = array("First chapter", "Second chapter", "Third chapter");
you can output this data as HTML:
echo "<ol>";
foreach ($array as $element) // Go through each array element and output an <li>
echo "<li>$element</li>";
echo "</ol>";
the result being (roughly)
<ol>
<li>First chapter</li>
<li>Second chapter</li>
<li>Third chapter</li>
</ol>
It depends on what type of file you are trying to write. Most often, PHP is writing a webpage in HTML, but not always. In HTML, if you want a numbered list, you should use an ordered list (<ol>).
If you're just writing a text file of some kind, incrementing and outputting a variable (like $i in your example) should work.
You mention Wordpress, so it's worth noting that if you worked on a Wordpress template before, you were using dozens of special functions in the Wordpress library, even though you may not have been completely aware that was what you were doing. A lot of the PHP heavy lifting is hidden and simplified for the templating engine, and if your current project is not built on that engine, you will have to do that logic yourself.
Related
The requirement is to add an englishText class around all english words on a page. The problem is similar to this, but the Javascript solutions wont work for me. I require a PHP example to solve this problem. For example, if you have this:
<p>Hello, 你好</p>
<div>It is me, 你好</div>
<strong>你好, how are you</strong>
Afterwards I need to end with:
<p><span class="englishText">Hello</span>, 你好</p>
<div><span class="englishText">It is me</span>, 你好</div>
<strong>你好, <span class="englishText">how are you</span></strong>
There are more complicated cases, such as:
<strong>你好, TEXT?</strong>
<div>It is me, 你好</div>
This should become:
<strong>你好, <span class="englishText">TEXT?</span></strong>
<div><span class="englishText">It is me</span>, 你好</div>
But I think I can sort out these edge cases once I know how actually iterate over the document correctly.
I can't use javascript to solve this because:
This needs to work on browsers that don't support javascript
I would prefer to have the classes in place on page load so there isn't any delay in rendering the text in the correct font.
I figured the best way to iterate over the document would be using PHP Simple HTML DOM Parser.
But the problem is that if I try this:
foreach ($html->find('div') as $element)
{
// make changes here
}
My concern is that the following case will cause chaos:
<div>
Hello , 你好
<div>Hello, 你好</div>
</div>
As you can see, it's going to go into the first div and then if I process that node, I will be processing the node within that too.
Any ideas how to get around this and only select the nodes for processing once?
UPDATE
I realise now that what I effectively need is a recursive way to iterate over HTML elements with the ability to change them as I iterate over them.
You should travel through siblings that way you won't get in trouble with such a cases...
Something like that:
<?php
foreach ($html->find('div') as $element)
{
foreach($element->next_sibling() as $sibling){
echo $sibling->plaintext()."\n";
}
}
?>
Or much easier way imo:
Just...
Change every <*> to "\n"."<*>" with preg_replace();
Make an array of lines like $lines = explode("\n",$html_string);
3.
foreach($lines as $line){
$text = strip_tags($line);
echo $text;
}
I'm rather new to programming and i know how to separate PHP from HTML, but i would like to know if there is any difference in doing
this:
<?php $rand="I love apples" ?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<?php echo"The variable contains the string $rand"; ?>
</div>
?>
compared to doing this:
<?php
echo "<h1>This is a title</h1>";
echo "<div>";
echo "<p>This is a paragraph</p>";
echo "The variable contains the string $rand";
echo "</div>";
?>
Is there any difference between in performance etc, between splitting the PHP code from the HTML code and just echoing the whole page in php?
The best practice is not to seperate PHP from HTML, the best practice is to seperate logic from markup.
Also important is coding style. Proper line indentions. Using echo "</div>"; instead of echo"</div>";, valid HTML, not putting variables into quotations:
echo "The variable contains the string $rand";
better (why? see my comment below):
echo "The variable contains the string ",
$rand,
" :-)";
Your whole project gains much quality and worthness just by improving the code, writing clean, readable, maintainable. Imagine you want to change the Text, you would have to add or change lots of echoes.
Code Style Guides > Pear,
PSR, Zend <
encourage developers to keep their code readable, valid and cross-browser compatible
The problem is not performance, it's about readability and more importantly, maintainability.
Doing all the processing in one place, and all of the output in another (i.e. Logic and Presentation), would mean you will have an easier time altering one without affecting the other too drastically.
To your specific question, the top method is preferable by far, for the reasons listed above.
Taking your question at face value, there are two reasons that come to mind immediately:
Assuming you're using a smart editor, echoing all your HTML will cause you to lose syntax highlighting for it, so you're less likely to catch errors.
Because everything is inside a PHP string, now you have to worry about escaping all your other special characters. Try spitting out some Javascript with a string in it and let us know how fun that is.
However, when most people say something like "separating PHP from HTML" they are referring to the concept of separating your logic from your views. It means don't put complex business logic, computations, and database calls inside your html pages. Keep that all in pure PHP files, and have your html files contain minimal PHP that's only used to spit out your data.
<?php $rand="I love apples" ?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<?php echo"The variable contains the string $rand"; ?>
</div>
?>
The above looks poorly separated. This is what php/html separation should look like:
<?php
$rand="I love apples";
?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<p>The variable contains the string <?=$rand ?></p>
</div>
Performance-wise, that's not an issue but it would do much favor for programmers to be able to read the code easily, hence the need for HTML/PHP separation practices. Ideally, if you're going to do just one script, keep all your PHP code at top. Also, other reason for the separation is that IDE editors can easily format HTML nicely. If there's a HTML tag inside the PHP tag that is ending with a HTML tag outside of PHP, then HTML cannot be formatted correctly. For example:
<div><p>And it offers so much <?php echo "$features</p>
<h2>Proven Ideas";?></h2>
<p>More details ahead</p>
</div>
The above will run just fine but the IDE html formatter will likely be confused with missing end tags and won't format making it more difficult for programmers to read them.
I think you example is not a good one that makes it very clear why you should separate it.
The reason why you should separate not just HTML but the presentation, rendering or UI part of your application is clean coding and separation of concerns. This will make sure your get clean, easy to read code and makes your application maintable.
Take Wordpress for example, it is an extremely fugly mix of php and HTML. They even do SQL queries in the presentation layer of the application, if you can even draw a borderline between presentation and other logic in this thing.
You'll always have to output some dynamic content in your HTML but really try to reduce it to echoing variables and having some output formatting helper objects there. All business logic should be somewhere else, just not in the "templates" or whatever else you'll call the files that contain the output.
Have a look at the MVC pattern for example, it gives you a good idea of how and why you want to separate things.
In my opinion, it depends on the level of HTML formatting that is being done versus PHP logic. Nothing more & nothing less. It’s simply easier to read pure HTML as pure HTML or PHP as straight PHP. When it is all jummbled together—the way some templating systems handle it—it becomes a logical headache to read & debug. So I err on the side of placing HTML in PHP for my own sanity’s sake.
Unclear on the performance pluses or minuses if there are any. But can assure you that in 20+ years I have never had a server slow down because of too much HTML embedded in PHP
Personally, I would format your code example like this:
<?php
echo "<h1>This is a title</h1>"
. "<div>"
. "<p>This is a paragraph</p>"
. "The variable contains the string $rand"
. "</div>"
;
?>
I like this method since there is one echo—which makes it clear what is happening—and the rest of the HTML is just concatenated via . characters.
Also, remember all formatting in programming benefits HUMANS more than anything. A computer only needs to see the commands, so if you want to be pitch perfect for a machine, just code without any spaces or formatting. Heck, stop using full words & just use 1 letter variables! Oh wait, that is how it was done in ye olden days.
Nowadays compilers & caching systems are designed to take human readable code & make it machine optimized.
Which is all to say: You should code towards readability & logic on your part. Nothing more & nothing less.
My PHP tends output html in really long, difficult to read html.
If my PHP is written as:
<?php
echo "<li>";
echo "<strong>Hello</strong>";
echo "</li>";
?>
it outputs HTML like this
<li><strong>Hello</strong></li>
which dosnt look that bad, but imagine if thats within a foreach loop which out putted variants of that, all on one line..
Is there a way to get my PHP to output as neatly composed HTML ?
There is: include the whitespace in your output (for example, add \n after each tag).
However, doing that is really an exercise in futility. If you want to view the HTML yourself, get an HTML pretty printer (or use the one included in your browser's developer tools). If it's meant for a browser, the browser doesn't care.
Use a template engine like SMARTY. This will allow you to keep all your html in completely different files than your PHP (it does compile as PHP). This will improve the readability of all of your code. You can then format the html any way you see fit.
You can use the \n to make a line break.
<?php
echo "<li>\n";
echo "<strong>Hello</strong>\n";
echo "</li>\n";
?>
But why use your time on it? Chrome details console will fix it if its because you use the html source as a debug tool.
Whether this is nice or not is subjective, but it works:
<?php
for ($i = 0; $i < 5; $i++)
{
?>
<li><strong>Hello</strong></li>
<?php
}
?>
What I'm trying to get at here is that you can go in and out of PHP mode, so if you have long strands of HTML, you can format them as such, instead of echoing everything.
I am not understanding I have this right now is the tables for html will work with PHP or are they different. I understand how to do tables in HTML with the CSS but I am not to sure with PHP. I am new to PHP and this might be a stupid question to most of you. I am just hoping someone can explain so I have a better understanding of it.
I am still not understanding how to display something in a table.
The browser only reads html.
PHP is a programing language, interpreted by the server, used to generate html that the browser reads.
That said there are no such thing as PHP tables. Just do a table the normal way. Take a look at the example bellow that uses PHP to create a "dynamic" table. Now imagine that the $animals gets pulled from a database...
Example:
my-table-generator.php
<?php
$animals = array("dog", "cat", "duck");
?>
<table>
<tr>
<?php
foreach($animals as $animal)
{
echo "<td>".$animal."</td>";
}
?>
</tr>
</table>
PHP helps you send dynamic HTML to the browser. The HTML always remain the same regardless of the backend language you are using. So just use regular HTML and use PHP to render it. For instance if you want to display multiple rows of some data coming from the DB, you will utilize a PHP loop to print out the <tr><td></td></tr>
example:
for($i = 0 ; $i < 10 ; $i++){
echo "<tr><td>$i</td></tr>";
}
Probably not a very good example but hopefully it will get the message across.
This question already has answers here:
How to properly indent PHP/HTML mixed code? [closed]
(6 answers)
Closed 9 years ago.
This has been bugging me today after checking the source out on a site. I use PHP output in my templates for dynamic content. The templates start out in html only, and are cleanly indented and formatted. The PHP content is then added in and indented to match the html formating.
<ul>
<li>nav1</li>
<li>nav2</li>
<li>nav3</li>
</ul>
Becomes:
<ul>
<?php foreach($navitems as $nav):?>
<li><?=$nav?></li>
<?php endforeach; ?>
</ul>
When output in html, the encapsulated PHP lines are dropped but the white space used to format them are left in and throws the view source formatting all out of whack. The site I mentioned is cleanly formatted on the view source output. Should I assume they are using some template engine? Also would there be any way to clean up the kind of templates I have? with out manually removing the whitespace and sacrificing readability on the dev side?
That's something that's bugging me, too. The best you can do is using tidy to postprocess the text. Add this line to the start of your page (and be prepared for output buffering havoc when you encounter your first PHP error with output buffering on):
ob_start('ob_tidyhandler');
You can't really get clean output from inlining PHP. I would strongly suggest using some kind of templating engine such as Smarty. Aside from the clean output, template engines have the advantage of maintaining some separation between your code and your design, increasing the maintainability and readability of complex websites.
i admit, i like clean, nicely indented html too. often it doesn't work out the way i want, because of the same reasons you're having. sometimes manual indentation and linebreaks are not preserverd, or it doesn't work because of subtemplates where you reset indentation.
and the machines really don't care. not about whitespace, not about comments, the only thing they might care about is minified stuff, so additional whitespace and comments are actually counter-productive. but it's so pretty *sigh*
sometimes, if firebugs not available, i just like it for debugging. because of that most of the time i have an option to activate html tidy manually for the current request. be careful: tidy automatically corrects certain errors (depending on the configuration options), so it may actually hide errors from you.
Does "pretty" HTML output matter? You'll be pasting the output HTML into an editor whenever you want to poke through it, and the editor will presumably have the option to format it correctly (or you need to switch editors!).
I find the suggestions to use an additional templating language (because that's exactly what PHP is) abhorrent. You'd slow down each and every page to correct the odd space or tab? If anything, I would go the other direction and lean towards running each page through a tool to remove the remaining whitespace.
The way I do it is:
<ul>
<?php foreach($navitems as $nav):?>
<li><?=$nav?></li>
<?php endforeach; ?>
</ul>
Basically all my conditionals and loop blocks are flush left within the views. If they are nested, I indent inside the PHP start tag, like so:
<ul>
<?php foreach($navitems as $nav):?>
<?php if($nav!== null) : ?>
<li><?=$nav?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
This way, I see the presentation logic clearly when I skim the code, and it makes for clean HTML output as well. The output inside the blocks are exactly where I put them.
A warning though, PHP eats newlines after the closing tag ?>. This becomes a problem when you do something like outputting inside a <pre> block.
<pre>
<?php foreach($vars as $var ) ?>
<?=$var?>
<?php endforeach; ?>
</pre>
This will output:
<pre>
0 1 2 3 4 5 </pre>
This is kind of a hack, but adding a space after the <?=$var?> makes it clean.
Sorry for the excessive code blocks, but this has been bugging me for a long time as well. Hope it helps, after about 7 months.
You few times I have tidied my output for debugging my generated HTML code I have used tabs and newlines... ie;
print "<table>\n";
print "\t<tr>\n";
print "\t\t<td>\n";
print "\t\t\tMy Content!\n";
print "\t\t</td>\n";
print "\t</tr>\n";
print "</table>\n";
I about fell over when I read "I'm really curious why you think it's important to have generated HTML that's "readable". Unfortunately, there were quite a few people on this page (and elsewhere) that think this way...that the browser reads it the same so why worry about the way the code looks.
First, keeping the "code" readable makes debugging (or working in it in general by you or a developer in the future) much easier in almost all cases.
Furthermore, AND MOST IMPORTANTLY, it's referred to as quality of workmanship. It's the difference between a Yugo and a Mercedes. Yes, they are both cars and they both will take you from point "A" to point "B". But, the difference is in the quality of the product with mostly what is not seen. There is nothing worse than jumping into a project and first having to clean up someone else's code just to be able to make sense of things, all because they figured that it still works the same and have no pride in what they do. Cleaner code will ALWAYS benefit you and anyone else that has to deal with it not to mention reflect a level of pride and expertise in what you do.
If it's REAL important in your specific case, you could do this...
<ul><?php foreach($navitems as $nav):?>
<li><?=$nav?></li><?php endforeach; ?>
</ul>
Although that is worse in my opinion, because your code is less readable, even though the HTML is as you desire.
I don't care how clean the output is - it's the original source code that produced it that has to be easy to parse - for me as a developer.
If I was examining the output, I'll run it through tidy to clean it up, if it were required to take a good look at it - but validators don't care about extra spaces or tabs either.
In fact, I'm more likely to strip whitespace out of the output HTML than put any in - less bytes on the wire = faster downloads. not by much, but sometimes it would help in a high traffic scenario (though of course, gzipping the output helps more).
Viewing unformatted source is very annoying with multiple nested divs and many records each containing these divs..
I came across this firefox addon called Phoenix Editor. You can view your source in it's editor and then click "format" and it works like a charm!
Link Here
Try xtemplate http://www.phpxtemplate.org/HomePage its not as well documented as id like, but ive used it to great effect
you would have something like this
<?php
$response = new xtemplate('template.htm');
foreach($navitems as $item)
{
$response->assign('stuff',$item);
$response->parse('main.thelist');
}
$response->parse('main');
$response.out('main');
?>
And the html file would contain
<! -- BEGIN: main -->
<html>
<head></head>
<body>
<ul>
<! -- BEGIN: thelist -->
<li>{stuff}</li>
<!-- END: thelist -->
</ul>
</body>
</html>
I Agree, A clean source is very important, Its well commented, well structured and maintence on those sources, scripts, or code is very quick and simple. You should look into fragmenting your main, using require (prior.php, header.php, title.php, content.php, post.php) in the corresponding places, then write a new function under prior.php that will parse and layout html tags using the explode method and a string splitter, have an integer for tab index, and whenever </ is in the functions string then integer-- whenever < and > but not /> and </ are in the string integer ++ and it all has to be placed properly.... , use a for loop to rebuild another string tabindex to tab the contents integer times.