How to include php to html

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

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

PHP в HTML

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

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

Читайте также:  Ошибка update cpp 1205 при установке драйвера

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

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

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

Источник

Learning PHP for WordPress Development: How to Include PHP in HTML

how to include php in html

Welcome to this article on how to use PHP in HTML! Here, we try to get specific about exactly how PHP and HTML interact, at the level of a specific .php file. In other words, how do you actually include PHP in HTML, and what rules can and can’t you follow in weaving PHP and HTML together?

This article is part of our series explaining the basics of PHP for WordPress development, and builds on knowledge from two previous articles:

  1. PHP’s echo . echo is how PHP outputs things to the page. For the purposes of this article, it’s basically PHP’s “turn this into HTML” button.
  2. PHP functions. Functions are units of work that only run when they are called (invoked), and this article gets into how that sense of “control flow” affects the HTML output that is actually sent to the browser.

As a last note: to learn what works and doesn’t for using PHP in HTML, concrete examples are more helpful than theory. So the bulk of this article is examples of PHP’s proper use within HTML, with comments for each code example.

How to Include PHP in HTML: File Types and Other Considerations

By default, you can’t use PHP in HTML files, meaning files that end with .html .

The first thing to know is that, by default, you can’t use PHP in HTML files, meaning files that end with .html . It’s possible to configure your server to allow PHP in .html files, but that’s outside our scope—so for now, just remember that, if you want to write PHP, you want to be working with .php files.

In a WordPress environment, that’s largely taken care of: the entirety of WordPress is PHP-based, so you will very frequently be working with .php files, and almost never with .html files.

There’s nothing about a .php file that makes it inherently “different” than a .html file, except that it can run PHP.

The other thing you should know is this: a .php file can run exactly like a .html file, with absolutely no PHP. In other words, there’s nothing about a .php file that makes it inherently “different” than a .html file, except that it can run PHP.

A few code examples will make it clearer what we mean by this.

How .html Files Respond to HTML and PHP

Imagine we have a file, index.html , that has the following contents:

Accessing this index.html file in your web browser would give you the following output:

I am HTML markup.

Now what if we added the following to index.html :

 

I am HTML markup.

And I am PHP.

'; ?>

Accessing this index.html file in your web browser would give you the following output:

I am HTML markup.

And I am PHP.

‘; ?> Definitely not what we want. The issue is that, by default, HTML files don’t “speak” PHP.

How .php Files Respond to HTML and PHP

Now, what if we simply renamed index.html to index.php and ran both examples again?

This would output

I am HTML markup.

, exactly as before. In other words, there’s no need to actually write PHP into .php files: PHP files handle plain HTML just fine.

 

I am HTML markup.

And I am PHP.

'; ?>

This would output the following clean HTML:

I am HTML markup.

And I am PHP.

This example demonstrates that PHP files (that is, .php files) can automatically interpret PHP code—anything inside the tag—and turn the resulting output into HTML.

Basic Use of PHP in HTML

Here are the basics of how to include PHP in HTML. This relies on knowledge of PHP’s echo statement, which we’ve covered in a previous article.

Printing HTML Content with PHP’s echo

To output HTML content within PHP, echo it:

Output to browser will be:

Hello

Outputting HTML Tags Using PHP

You can use PHP to output HTML tags into the page’s markup:

Output to browser will be:

Hello

Using PHP Inside HTML Tags

PHP can go anywhere, including inside HTML tag declarations, and including inside quotes ( » ):

Output to browser will be:

Hello

Details on Opening and Closing the PHP Tag in HTML

This section relies on a basic understanding of PHP functions, which we’ve covered in an earlier article.

Opening and Closing the PHP Tag

You can swap between HTML and PHP at any time by opening ( ) the PHP tag:

I came from PHP.

' ?>

And I came from HTML.

Back to PHP and '; ?>now HTML.

Output to browser will be:

I came from PHP.

And I came from HTML.

Back to PHP and now HTML.

Line Breaks in PHP Code

Line breaks (as well as spaces and indentation) can work any way within the PHP tag:

I am PHP.

'; echo '

Still PHP.

'; ?>

Now HTML.

Output to browser will be:

I am PHP.

Still PHP.

Now HTML.

HTML Inside PHP Operators

HTML can go inside PHP operators of all kinds–such as if() -statements and functions, and will simply print like echo when the relevant lines of code are run.

 

HTML output from inside function.

?>

Output to browser will be

HTML output from inside function.

You can close a PHP tag, and revert to plain HTML, inside a function definition, if() -statement, or other PHP operator.

Another way to describe this code example is to note that you can close a PHP tag, and revert to plain HTML, inside a function definition, if() -statement, or other PHP operator.

Those lines of HTML will print to the page when they are executed, which depends on the control flow of the PHP logic on the page.

Declarations from Previous Tags Are Still Stored

PHP will remember variables, functions, and other declarations from previously opened and closed PHP tags higher on the page:

 

Hello from function.

?>
Plain HTML between two PHP tags.
Hello from variable.'; ?>
Plain HTML between two PHP tags again.

Output to browser will be:

Plain HTML between two PHP tags.
Plain HTML between two PHP tags again.

Hello from function.

Hello from variable.

Controlling HTML Output with PHP Operators

PHP can control the logic flow across the page, altering output.

Iterating HTML Output Using a while() Loop

Here’s an example that iterates (repeats) HTML output using a PHP while() loop:

 

$i = 0; // $i starts out at 0 // This while()-loop will keep running as long as $i is less than 3 Hello $i++; // This means "increase $i by 1"

Inserting Dynamic Values into HTML Using PHP

Inserting dynamic values—values that are not pre-defined, but change as variables—into HTML using a PHP while() loop:

Output to browser will be:

Number 0Number 1Number 2

This basic pattern—dynamic HTML output within a PHP while loop—is shared by WordPress’s content engine, the Loop.

Controlling HTML Output Using PHP Conditionals

You can control HTML output using PHP conditionals ( if() -statements):

 

Now you see me

?>

Now you don't

?>

Output to browser will be:

Now you see me

In the example above, we asked two things, one which is always true and one which is always false:

  1. “Does 1 equal 1?” (This is always true, so the code inside its if statement will always run, printing that HTML to the page.)
  2. “Does 1 equal 2?” (This is never true, so the code inside its if statement will never run, and its HTML does not print to the page.)

And That’s Our PHP-in-HTML Primer

Hopefully these code examples have given you a good sense of some of the basics of how to add PHP to HTML, and how PHP and HTML interact in practice.

Источник

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