Вывести блок html на php

Содержание
  1. Как вставить HTML, CSS и JS в PHP-код?
  2. Первый вариант вставки элементов в PHP-код
  3. Второй вариант вставки элементов в PHP-код
  4. How can I get a div content in php
  5. 3 Answers 3
  6. Is there any way to return HTML in a PHP function? (without building the return value as a string)
  7. 8 Answers 8
  8. $replStr
  9. Yes, there is: you can capture the echo ed text using ob_start : Exactly, this way syntax is highlighted and key words are colored as they would being normal HTML, other than being content in a string. Definitely a better answer for maintainability, which should always come first Why would you use the output buffer when this seems to work fine? Lorem ipsum dolar ?> This may be a sketchy solution, and I’d appreciate anybody pointing out whether this is a bad idea, since it’s not a standard use of functions. I’ve had some success getting HTML out of a PHP function without building the return value as a string with the following: function noStrings() < echo ''?>[Whatever HTML you want] The just ‘call’ the function: Using this method, you can also define PHP variables within the function and echo them out inside the HTML. At least in PHP 8.1.12 on Windows, keep in mind that you need whitespace after the Create a template file and use a template engine to read/update the file. It will increase your code’s maintainability in the future as well as separate display from logic. Template File function TestBlockHTML()< $smarty = new Smarty(); $smarty->assign('title', 'My Title'); $smarty->assign('string', $replStr); return $smarty->render('template.tpl'); > Winging some old PHP code. This is solid, thanks! I had to use Smarty’s display method instead of render . Another way to do is is to use file_get_contents() and have a template HTML page function YOURFUNCTIONNAME($url) This is the closest to what I’m looking for. @Cayde 6, do you think theres a way to have a single file ‘template.php’, containing both the php function and html? So then anywhere in my site, I just ‘require_once(‘template.php’)’, then call echo the function wherever I need that html to appear. In the YOURFUNCTIONNAME($url), would the $url would need to be itself? How can we do that? Thanks Источник How can I echo HTML in PHP? I want to conditionally output HTML to generate a page, so what’s the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty? echo '', "\n"; // I'm sure there's a better way! echo '', "\n"; echo '', "\n"; echo '', "\n"; echo '', "\n"; echo '', "\n"; Good pracitice say to separete your logic from view (like in MVC). use templetig engine like Twig to separete your view from script logic — twig.sensiolabs.org Insted of implementing your html markup to your php script do it other way round. Implement php variables to twig temple. As soon as you get what I mean you will see benefits of this aproach. Twig solve this kind of issues. For small chank of code you can write your own twig extension which you can then use with in secounds to performe some complicated but repetative tasks. 13 Answers 13 There are a few ways to echo HTML in PHP. 1. In between PHP tags 2. In an echo With echos, if you wish to use double quotes in your HTML you must use single quote echos like so: Or you can escape them like so: 3. Heredocs 4. Nowdocs (as of PHP 5.3.0) Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP’s original purpose was to be a templating language. That’s why with PHP you can use things like short tags to echo variables (e.g. ). There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. > ). The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run. If you have any more questions feel free to leave a comment. Further reading is available on these things in the PHP documentation. NOTE: PHP short tags are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the —enable-short-tags option. They are available, regardless of settings from 5.4 onwards. Источник
  10. How can I echo HTML in PHP?
  11. 13 Answers 13
  12. 1. In between PHP tags
  13. 2. In an echo
  14. 3. Heredocs
  15. 4. Nowdocs (as of PHP 5.3.0)
Читайте также:  Кортеж словарь множество python

Как вставить HTML, CSS и JS в PHP-код?

Когда вы разрабатываете свой модуль, то иногда прибегаете к помощи верстки (HTML и CSS) и дополнительным скриптам.

Все это можно подключать отдельно – что-то в теле страницы, что-то в отдельных файлах. Но некоторые дополнения лучше вставлять непосредственно в сам PHP-файл.

Сегодня я покажу два варианта, как можно вставить HTML, CSS или JavaScript в код PHP.

Первый вариант вставки элементов в PHP-код

Я думаю, что если вы хоть немного знакомы с PHP, то знаете, что такое «echo» (тег, с помощью которого вы можете вывести сообщение на экран).

Вот с помощью него и можно вывести один из перечисленных ранее кодов. Пример:

   "; echo $content; ?>

На что здесь стоит обратить внимание? Кавычки. Если вы используете внешние кавычки в виде » «, то внутренние кавычки элементов должны быть ‘ ‘ и наоборот, иначе вы получите ошибку. Если вы принципиально хотите использовать одинаковые и внешние, и внутренние кавычки, то во внутренних ставьте знак экранизации:

   "; echo $content; ?>

В этом случае все будет работать корректно.

Второй вариант вставки элементов в PHP-код

Этот вариант мне нравится куда больше, чем первый. Здесь мы будем также использовать «echo», как и в предыдущем варианте, но добавим еще элемент «HTML»:

Сюда вы можете вставлять любой элемент, будь то HTML-код или же JavaScript. Кавычки здесь не играют роли (можете вставить любые), а по желанию можно внедрить переменные для вывода:

 "; echo    HTML; ?>

Весьма удобный способ для реализации ваших идей.

Источник

How can I get a div content in php

Am I correct that the last line in your ‘UPDATED’ code declaring $id should follow with a semicolon for PHP syntax?

3 Answers 3

$dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXPath($dom); $divContent = $xpath->query('//div[@id="product_list"]'); 

Are any external libraries required to run the code you pasted here? I ask this because the code does not seem to work directly on my server.

No, but requires the libxml PHP extension. php.net/manual/en/dom.requirements.php Check your phpinfo(). Have you got any error message?

This does not retrieve the HTML, it retrieves an object with one property: length . The correct answer is the one provided by stackoverflow.com/users/497139/thw just below. Direct link: not possible on SO for whatever reason.

To save an XML/HTML fragment, you need to save each child node:

$dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXPath($dom); $result = ''; foreach($xpath->evaluate('//div[@id="product_list"]/node()') as $childNode) < $result .= $dom->saveHtml($childNode); > var_dump($result); 
string(74) " 
bla bla bla
bla bla "

If you only need the text content, you can fetch it directly:

$dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXPath($dom); var_dump( $xpath->evaluate('string(//div[@id="product_list"])') ); 
string(63) " bla bla bla bla bla " 

Источник

Is there any way to return HTML in a PHP function? (without building the return value as a string)

I have a PHP function that I’m using to output a standard block of HTML. It currently looks like this:

I want to return (rather than echo) the HTML inside the function. Is there any way to do this without building up the HTML (above) in a string?

8 Answers 8

You can use a heredoc, which supports variable interpolation, making it look fairly neat:

function TestBlockHTML ($replStr) < return HTML; > 

Pay close attention to the warning in the manual though — the closing line must not contain any whitespace, so can’t be indented.

Also the
You can avoid braces if the var is non into an array:

$replStr

or

Yes, there is: you can capture the echo ed text using ob_start :

Exactly, this way syntax is highlighted and key words are colored as they would being normal HTML, other than being content in a string. Definitely a better answer for maintainability, which should always come first

Why would you use the output buffer when this seems to work fine?

Lorem ipsum dolar

?>

This may be a sketchy solution, and I’d appreciate anybody pointing out whether this is a bad idea, since it’s not a standard use of functions. I’ve had some success getting HTML out of a PHP function without building the return value as a string with the following:

function noStrings() < echo ''?>
[Whatever HTML you want]

The just ‘call’ the function:

Using this method, you can also define PHP variables within the function and echo them out inside the HTML.

At least in PHP 8.1.12 on Windows, keep in mind that you need whitespace after the

Create a template file and use a template engine to read/update the file. It will increase your code’s maintainability in the future as well as separate display from logic.

Template File

function TestBlockHTML()< $smarty = new Smarty(); $smarty->assign('title', 'My Title'); $smarty->assign('string', $replStr); return $smarty->render('template.tpl'); > 

Winging some old PHP code. This is solid, thanks! I had to use Smarty’s display method instead of render .

Another way to do is is to use file_get_contents() and have a template HTML page

function YOURFUNCTIONNAME($url)

This is the closest to what I’m looking for. @Cayde 6, do you think theres a way to have a single file ‘template.php’, containing both the php function and html? So then anywhere in my site, I just ‘require_once(‘template.php’)’, then call echo the function wherever I need that html to appear. In the YOURFUNCTIONNAME($url), would the $url would need to be itself? How can we do that? Thanks

Источник

How can I echo HTML in PHP?

I want to conditionally output HTML to generate a page, so what’s the easiest way to echo multiline snippets of HTML in PHP 4+? Would I need to use a template framework like Smarty?

echo '', "\n"; // I'm sure there's a better way! echo '', "\n"; echo '', "\n"; echo '', "\n"; echo '', "\n"; echo '', "\n"; 

Good pracitice say to separete your logic from view (like in MVC). use templetig engine like Twig to separete your view from script logic — twig.sensiolabs.org Insted of implementing your html markup to your php script do it other way round. Implement php variables to twig temple. As soon as you get what I mean you will see benefits of this aproach. Twig solve this kind of issues. For small chank of code you can write your own twig extension which you can then use with in secounds to performe some complicated but repetative tasks.

13 Answers 13

There are a few ways to echo HTML in PHP.

1. In between PHP tags

2. In an echo

With echos, if you wish to use double quotes in your HTML you must use single quote echos like so:

Or you can escape them like so:

3. Heredocs

4. Nowdocs (as of PHP 5.3.0)

Template engines are used for using PHP in documents that contain mostly HTML. In fact, PHP’s original purpose was to be a templating language. That’s why with PHP you can use things like short tags to echo variables (e.g. ).

There are other template engines (such as Smarty, Twig, etc.) that make the syntax even more concise (e.g. > ).

The primary benefit of using a template engine is keeping the design (presentation logic) separate from the coding (business logic). It also makes the code cleaner and easier to maintain in the long run.

If you have any more questions feel free to leave a comment.

Further reading is available on these things in the PHP documentation.

NOTE: PHP short tags are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the —enable-short-tags option. They are available, regardless of settings from 5.4 onwards.

Источник

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