Как очистить страницу php
Перейти к содержимому

Как очистить страницу php

  • автор:

How to clear all elements in a page with PHP?

Is there any way to clear all html elements in a php page?

For example I have 100 html elements in my page, is there anyway to remove them?

As we know with javascript we have innerHTML but in PHP what?

Freeman's user avatar

4 Answers 4

clear all html elements in a php page

That doesn’t make sense. HTML elements only exist in the DOM after PHP has executed and sent an HTML document to the browser. Server-side, where PHP executes, there are no elements to remove.

If you’re trying to manipulate the HTML you’ve already output, you need to capture it with output buffering (see ob_start , ob_get_contents and ob_end_clean ) but if your goal is to «clear all html elements», presumably so you can output a different set of elements, you simply need to not output anything in the first case. If this sounds like what you’re trying to accomplish, you need to look into simple conditional statements like if / else .

as we know with javascript we have innerHTML but in php what ?

There is no PHP-equivalent because PHP doesn’t have access to the client-side DOM. It is purely a server-side technology, and the output of your PHP script is the input to the browser. The DOM and its elements are generated long after your PHP script has executed. If you have an XHTML fragment in a string, and you want to parse/manipulate it, you can use xpath.

ob_end_clean

This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_clean() will not work.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

Errors/Exceptions

If the function fails it generates an E_NOTICE .

Examples

The following example shows an easy way to get rid of all output buffers:

Example #1 ob_end_clean() example

See Also

  • ob_start() — Turn on output buffering
  • ob_get_contents() — Return the contents of the output buffer
  • ob_flush() — Flush (send) the output buffer

User Contributed Notes 12 notes

Take note that if you change zlib output compression setting in between ob_start and ob_end_clean or ob_end_flush, you will get an error: ob_end_flush() failed to delete buffer zlib output compression

ini_set ( ‘zlib.output_compression’ , ‘1’ );

?>

ob_end_clean(); in this example will throw the error.

Note that if you started called ob_start with a callback, that callback will still be called even if you discard the OB with ob_end_clean.

Because there is no way of removing the callback from the OB once you’ve set it, the only way to stop the callback function from having any effect is to do something like:

<?php
$ignore_callback = false ;
ob_start ( ‘my_callback’ );
.
if( $need_to_abort ) <
$ignore_callback = true ;
ob_end_clean ();
.
>

function my_callback (& $buffer ) <
if( $GLOBALS [ ‘ignore_callback’ ]) <
return «» ;
>
.
>
?>

If there is no confidence about output buffering (enabled or not),
you may try these guards:

while ( ob_get_level () !== 0 ) <
ob_end_clean ();
>

while ( ob_get_length () !== false ) <
ob_end_clean ();
>

Keep in mind that mrfritz379’s example (#49800) is just an example. You can achieve that example’s result in a more efficient manner without using output buffering functions:

echo «<p>Search running. Please be patient. . .»;
$output = «<p>FileList: </p>\n»;
if (is_dir($dir)) <
$dh = opendir($dir);

while (($fd = readdir($dh)) != false) <
echo » .»;
$output .= $fd;
>
>
echo «</br>Search Complete!</p>\n»;
echo $output;

In addition to John Smith’s comment (#42939), ob_gzhandler() may still set the HTTP header «Content-Encoding» to «gzip» or «deflate» even if you call ob_end_clean(). This will cause a problem in the following situation:

1. Call ob_gzhandler().
2. Echo «Some content»;
3. Call ob_end_clean().
4. Echo «New content»;

In the above case, the browser may receive the «Content-Encoding: gzip» HTTP header and attempts to decompress the uncompressed «New content». The browser will fail.

In the following situation, this behaviour will go unnoticed:

1. Call ob_gzhandler().
2. Echo «Some content»;
3. Call ob_end_clean().
4. Call ob_gzhandler().
5. Echo «New content»;

This is because the second ob_gzhandler() will mask the absence of the first ob_gzhandler().

A solution would be to write a wrapper, like John Smith did, for the ob_gzhandler().

You might want to prevent your script from executing if the client already has the latest version.
You can do it like so:

$mtime=filemtime($_SERVER[«SCRIPT_FILENAME»])-date(«Z»);
$gmt_mtime = date(‘D, d M Y H:i:s’, $mtime) . ‘ GMT’;

if(isset($headers[«If-Modified-Since»])) <
if ($headers[«If-Modified-Since»] == $gmt_mtime) <
header(«HTTP/1.1 304 Not Modified»);
ob_end_clean();
exit;
>
>

$size=ob_get_length();
header(«Last-Modified: «.$gmt_mtime);
header(«Content-Length: $size»);
ob_end_flush();

Instead of checking the If-Modified-Since-Header against the date of the last modification of the script, you can of course query a database or take any other date that is somehow related to the modification of the result of your script.

You can for instance use this technique to generate images dynamically. If the user indicates he already has a version of the image by the If-Modified-Since-Header, there’s no need to generate it and let the server finally discard it because the server only then interpretes the If-Modified-Since-Header.
This saves server load and shortens response-times.

Notice that ob_end_clean() does discard headers.

If you would like to clear the output buffer, but not the headers (because you use firephp for example. ), than this is the solution:

$headers = array();
if ( ! headers_sent () ) <
$headers = apache_response_headers ();
>

if ( !empty( $headers ) ) <
foreach ( $headers as $name => $value ) <
header ( » $name : $value » );
>
>

.
?>

I use it in a general exception handler in a web application, where I clear the buffer (but not the debug-info-containing headers), and send a 500 error page with readfile().

About the previous comment:
You can also relay on ETag and simply use time()

<?php
$time = time ();
$mins = 1 ;
if (isset( $_SERVER [ ‘HTTP_IF_NONE_MATCH’ ]) and str_replace ( ‘»‘ , » , $_SERVER [ ‘HTTP_IF_NONE_MATCH’ ])+( $mins * 60 ) > $time )
<
header ( ‘HTTP/1.1 304 Not Modified’ );
exit();
>
else
<
header ( ‘ETag: «‘ . $time . ‘»‘ );
>
echo ‘Caching for ‘ , $mins * 60 , ‘secs<br/>’ , date ( ‘G:i:s’ );
?>

This may be posted elsewhere, but I haven’t seen it.
To run a progress indicator while the program is running without outputting the output buffer, the following will work:

echo «<p>Search running. Please be patient. . .»;
$output = «<p>FileList: </p>\n»;
if (is_dir($dir)) <
$dh = opendir($dir);

while (($fd = readdir($dh)) != false) <
echo » .»;
ob_start();
echo $fd;
$output .= ob_get_contents();
ob_end_clean();
>
>
echo «</br>Search Complete!</p>\n»;
echo $output;

The program will continue to print the » .» without printing the file list. Then the «Search Complete» message will print followed by the buffered file list.

In reference to <geoff at spacevs dot com> where he states, «If you call ob_end_clean in a function registered with ‘register_shutdown_function’, it is too late, any buffers will have already been sent out to the client.», here is a workaround I came up with.

function ClearBuffer ( $Buffer ) <
return «» ;
>

function Shutdown () <
ob_start ( «ClearBuffer» );
>

?>

This will wipe out all the contents of the output buffer as it comes in. Basically its the same as «STDOUT > /dev/null».

To safely clear and close all non-lethal output buffers:

function ob_end_clean_all () <
$handlers = ob_list_handlers ();
while ( count ( $handlers ) > 0 && $handlers [ count ( $handlers ) — 1 ] != ‘ob_gzhandler’ && $handlers [ count ( $handlers ) — 1 ] != ‘zlib output compression’ ) <
ob_end_clean ();
$handlers = ob_list_handlers ();
>
>

PHP: очистить экран (или установить пустой экран)

Как я могу «стереть» любые ранее отображенные элементы [браузера]? -Очистить экран полностью (установить пустой экран)?

Проблема, с которой я сталкиваюсь, заключается в следующем. Страница отображает часть HTML, но когда она достигает ключевых слов, она останавливается и повторяет то, что мне нужно (предполагаемое поведение, если на странице нет ключевых слов).

Тем не менее, поскольку он не очищает экран и DOM … в результате экран браузера пуст без каких-либо сообщений об ошибках. Это потому, что мне нужно стереть любой ранее отраженный вывод.

Я попробовал ob_end_clean () перед публикацией этого вопроса. Но это не работает:

PHP:

На стороне HTML я использую . content=»<?php keywords::run(); ?>» /> , Если на странице нет ключевых слов, это вывод (без очистки браузера):

HTML

Есть ли причина, по которой вы не можете сделать следующее? Вы не должны выводить, пока не знаете, что хотите напечатать / echo

Exit завершит выполнение вашего скрипта, и я полагаю, что это не то поведение, которое вы ожидаете от него. Таким образом, ваш код не работает так, как вы могли ожидать, когда в документе нет ключевых слов:

Вы должны использовать «return» или другой способ выйти из «run», но не заканчивая выполнение скрипта PHP!

Например (оставив этот текст внутри тега ключевых слов):

Пример (не оставляя текста):

Этот текст можно использовать для предупреждения вызывающего абонента об этой проблеме, но в вашем коде он будет молча оставлять тэг ключевых слов пустым и при этом запускать оставшуюся часть сценария PHP.

С наилучшими пожеланиями.

Поскольку я понимаю вашу потребность, на самом деле вы не хотите очищать экран, а видите сообщение об ошибке в своем браузере, не глядя на исходный код. И это невозможно, потому что вы уже открыли теги.

Попробуйте это вместо вашего кода выхода:

Вы должны закрыть свой метатег, заголовок и запустить тег body.

Вы не можете уменьшить выход. Обычно сервер отправляет каждый вывод одновременно. Таким образом, отпечаток или эхо не может быть отменено. Но вы можете буферизовать вывод, начав весь код с ob_start ();

В конце вашего кода вы можете отправить свой буфер клиенту с ob_end_flush ();

Для вывода сведений об ошибке вы можете использовать пользовательскую функцию, например:

Это сделает ваш трюк.

НО

Будет гораздо лучше собрать всю информацию в вашу мета-версию, даже не отправляя html. Это приведет к более быстрой отправке клиенту. Вы просто выводите метас, если вся информация ясна:

Это часто используется в cms’ах, которые загружают пользовательские плагины. Люди, как правило, добавляют начальный ввод в конце файла или пробел / ввод перед первым <?php тэг, поэтому движок обычно открывает обработчик ob, а затем после того, как все было загружено (и до того, как шаблоны используются для вывода — он очищает буфер от всех ошибок, вводит и так далее).

How to clean HTML content in PHP?

Clean HTML content in PHP

After a long long time, i get time to write an article and I am curious to write but didn’t get time. So, Today I am going to explain about how to clean HTML content using PHP code.

Sometimes you want to remove HTML tags from your content.Especially when you want to display short description from the long description of content, following function is useful.It is very useful when we want to completely remove HTML code from the string.

Let’s see function to clean html content

Super Simple! This function can be very helpful to strip out all HTML tags.Here, An above little code snippet will take the sting and then used nl2br function which will replace \ n to HTML tag. then I have used preg_replace function which will replace all
tag to space. then trim and strip_tags which remove extra space and other HTML content respectively.

That’s it. Place above function into a file and call function and see magic ;).

Hope this helps someone else out.As always,Thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.

About Author

Bhumi

Bhumi shah is currently working with leading web development company as a Software Analyst and also the founder of the Creativedev. She has immense interest in programming and web designing.She is passionate about technical blogging and almost versatile in terms of programming across various languages & frameworks such as PHP,MySQL WordPress, Twitter Bootstrap, AngularJS, HTML5, CSS3, jQuery and more.

RELATED POST

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *