Html coding with php

Is there a better way to write HTML strings in PHP?

I find myself writing a lot of functions in PHP that return HTML code. They may look something like this:

return """ 
BARE XX DAGER IGJEN
"""

As you don’t have to escape quotation marks. An alternative is using single quotation marks, but that means no using PHP variables directly in the string. I swear I’ve seen something like this in PHP:

return  
BARE XX DAGER IGJEN

IMHO if you have your PHP script output «long HTML strings» like this you are doing something wrong. You should keep your logic (PHP code) and HTML separate. In this case put the HTML in a separate file and include it when needed.

php.net/heredoc will point you in the right direction. But in short label the

8 Answers 8

PHP knows several kinds of syntax to declare a string:

So you don’t have to use the double quotes per se.

If you need a method that can be used to store HTML into a string, this is the way to do it.

I would not use any of these other suggested methods lol, I would use an Output buffer. These other methods all seem mega dirty (because at scale there would be a lot of special characters flying around). so at the risk of offending someone i’ll just say the reasons why I like my way.

Читайте также:  Java keystore certificate list

If you use an output buffer like I have done.

When using an IDE you can still have great intelisense help with HTML and PHP separate from one another and still code out generic DOM Objects quickly.

When viewing the code it looks a lot more human readable.

The HTML code can be passed in its DOM ready state rather than as a string which will eventually need to be parsed and eventually created into a DOM ready state.

When using HTML as a string method it can get really rough trying to use the various string function search and replace methods in order to change some of your code after runtime. For example looking for the tag within a massive string of other HTML elements can be daunting especially when trying to find stuff between tags.

I would use the Output Buffer Stream like so.

ob_start(); ?> 
BARE XX DAGER IGJEN

Источник

Как подключить PHP к HTML?

PHP - это встраиваемый серверный язык программирования. Большая часть его синтаксиса заимствована из C , Java и Perl . А также добавлена пара уникальных характерных только для PHP функций . Основная цель этого языка - создание динамически генерируемых PHP HTML страниц .

PHP в HTML

При создании сложных веб-страниц вы столкнетесь с необходимостью объединить PHP и HTML для реализации конкретных задач. На первый взгляд это может показаться сложным, так как PHP и HTML являются двумя независимыми дисциплинами, но это не так. PHP предназначен для взаимодействия с HTML , и его код может быть включен в разметку страницы.

В HTML-страницы PHP-код включается с помощью специальных тегов. Когда пользователь открывает страницу, сервер обрабатывает PHP-код , а затем отправляет результат обработки ( не сам PHP-код ) в браузер.

HTML и PHP довольно просто объединить. Любая часть PHP-скрипта за пределами тегов игнорируется PHP-компилятором и передается непосредственно в браузер. Если посмотреть на пример, приведенный ниже, то можно увидеть, что полный PHP-скрипт может выглядеть следующим образом:

Приведенный выше код - это обычный HTML с небольшим фрагментом PHP , который выводит текущую дату, используя встроенную функцию date . При этом весь HTML будет игнорироваться PHP-компилятором и передаваться в браузер без изменений.

Интегрировать PHP в HTML действительно очень легко. Помните, что скрипт - это HTML-страница с включением определенного PHP кода . Можно создать скрипт, который будет содержать только HTML (без тегов ), и он будет нормально работать.

Источник

Your first PHP-enabled page

Create a file named hello.php and put it in your web server's root directory ( DOCUMENT_ROOT ) with the following content:

Example #1 Our first PHP script: hello.php

Use your browser to access the file with your web server's URL, ending with the /hello.php file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:

This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.

The point of the example is to show the special PHP tag format. In this example we used . You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.

Note: A Note on Line Feeds

Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.

Note: A Note on Text Editors

There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.

Note: A Note on Word Processors

Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.

Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.

Example #2 Get system information from PHP

Источник

PHP Syntax

A PHP script is executed on the server, and the plain HTML result is sent back to the browser.

Basic PHP Syntax

A PHP script can be placed anywhere in the document.

The default file extension for PHP files is " .php ".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function " echo " to output the text "Hello World!" on a web page:

Example

My first PHP page

Note: PHP statements end with a semicolon ( ; ).

PHP Case Sensitivity

In PHP, keywords (e.g. if , else , while , echo , etc.), classes, functions, and user-defined functions are not case-sensitive.

In the example below, all three echo statements below are equal and legal:

Example

Note: However; all variable names are case-sensitive!

Look at the example below; only the first statement will display the value of the $color variable! This is because $color , $COLOR , and $coLOR are treated as three different variables:

Example

$color = "red";
echo "My car is " . $color . "
";
echo "My house is " . $COLOR . "
";
echo "My boat is " . $coLOR . "
";
?>

PHP Exercises

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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