How do I remove text from the console in PHP? - php

My goal is to print an updating progress percentage to the console (in both Linux and Windows). Currently I just print out the percentage each 10%, but I would prefer that it updated itself every 1% without filling the screen with percentages.
Is it possible to remove text you have written to the console in PHP?

echo chr(8);
will print a backspace character.

very simple
Note the example below
$removeLine = function (int $count = 1) {
foreach (range(1,$count) as $value){
echo "\r\x1b[K"; // remove this line
echo "\033[1A\033[K"; // cursor back
}
};
echo "-----------------------------\n";
echo "--------- Start -----------\n";
echo "-----------------------------\n";
sleep(2);
$removeLine(3);
echo 'hi';
sleep(2);
$removeLine();
echo 'how are you ?';
die();

See Zend_ProgressBar

PEAR's Console_ProgressBar is useful for this sort of use case.
To clear the console entirely, you can use:
if($_SERVER['SHELL']) {
print chr(27) . "[H" . chr(27) . "[2J";
}
which is quite a bit easier than keeping track of how many characters to backspace.

Related

insert line break php function

I have an issue where I'm showing boxes of some posts from my database in a foreach loop.
The length of the post title affects the design. For example if one post has a long title next to one with a short title, it will push the link i have below down. This makes it look uneven.
Therefor I'm trying to write a function that checks if the length is too short, it should insert a line break.
This is what I have so far.
function insert_line_break($text){
if (strlen($text) < 10 ) {
echo "<br>";
}
}
<?= insert_line_break($entry["title"]) ?>
However that seems to replace the title with a linebreak.
What am I missing?
You have missed to echo the text itself.
function insert_line_break($text){
if (strlen($text) < 10 ) {
return "<br>";
}
}
<?php echo $entry["title"] . insert_line_break($entry["title"]); ?>
Note:
I changed the function to return a value instead of echoing it to the output, so it will be much more reusable in the future.
And I expanded the short tag <? to <?php and made the = to verbose echo which is much clearer and readable way of coding.
And of course I closed the line with semicolon ; as it should be.
EDIT:
<?php echo $entry["title"] . insert_line_break($entry["title"]); ?>
echo prints the content of $entry["title"] and then ask function insert_line_break($entry["title"]) to decide whether it contains string shorter than 10 characters, if so it returns <br> that is echoed. And that's it.

html_entity_decode nesting php

running php 5.6.29 here.
Processing about 6,000 rows of data from a MYSQL Table. Looking at the HTML Description column and making changes. Using html_entity_decode to show the changed result in the Browser.
The problem is, each row is displaying the HTML result nested inside the previous row, which makes the display impossible. Obviously I want each row to have a clean break. As these are tables, it seems not to break?
while ($row = mysqli_fetch_array($result))
{
$i++;
echo "<br>$i";
echo "<br>Product: ".$row['id'];
echo "<br>Title: ".$row['title'];
echo "<br>";
$a = $row['html'];
echo "htmlspecialchars_decode($a)";
//...change the html process here ...
$b = html_entity_decode($row['html']);
echo "<br><br><br>".$b;
echo "<br>";
echo "<br>";
echo "<br>";
echo "<br>";
}
I checked this in multiple browsers, so it's not just Chrome. Basically I somehow need to close the HTML before I move onto the next row right? Or is this some kind of limitation or bug? tia.

PHP echo adding functions

What I am trying to do is get an echo of the following php call and subtract 14.1% from the displayed number.
The code:
<?php echo $program->current_amount(); ?>
Can I add arithmetic functions to this in order to display the 14.1% deduction?
I think you're looking for a basic math operation in your output that has no effect on a database or anything else, correct?
If so, do something like the following:
<?php
// Set values
$current_amount = 100;
$pcnt_off = 14.1;
// Do the math
$out = $current_amount - ($pcnt_off/100) * $current_amount;
// Output
echo $out . " is " . $pcnt_off . "% off of " . $current_amount;
?>
http://codepad.org/RqF8cuvN
More specifically to your case:
<?php echo $program->current_amount() - 0.141 * $program->current_amount(); ?>
You can perform expressions inside an echo statement, yes; just wrap it in a (), so:
<?php echo ($program->current_amount() - .141); ?>
It may not even be necessary to use (). Incidentally, if your environment supports short tags, you can simply do:
<?= $program->current_amount() - .141 ?>
Keep in mind, though, that that code won't actually remove 14.1% from your number--you would want to multiply by .859.

HTML a tag causes wide spaces

I have a sentence in PHP that I've broken down into its word components using explode.
foreach ($words as $splitword)
{
echo $splitword;
/* echo "<a href = 'word.php?word=" . $splitword . "'>" . $splitword . "</a>"; */
echo " ";
}
What I want to do is make each word clickable, so I echo each word followed by a space. Now, using the code you see above, everything looks fine and natural. However, if I uncomment the commented line, and comment out echo $splitword;, so that I'm now echoing links instead of just the word, things get ugly:
echo " " no longer works, I have to use echo "&nbsp"
The spaces are very large. Echoing each word without making it a link produces natural spacing, the way it should be. But when I start using the a tag followed by &nbsp, the spaces are about twice as wide.
Any idea why, and what a workaround is?
echo " " does not work because you are writing HTML, which does not parse " ".
You'll have to use like you already discovered.
The extra spacing could be your styling. Check your CSS. If you still don't find anything strange, add this to your CSS:
a {
margin: 0;
padding: 0;
}

printing process output in realtime

I am using PHP 5.3.4 with Apache 2.2.17 on a Windows 7 x64 system. I would like to have my PHP page output the result of a system call in real-time to the user's browser. To that end, I have configured output_buffering=Off in php.ini and created this code:
<?php
ob_implicit_flush(true);
ob_end_flush();
system('ping -n 10 www.google.com');
?>
The result of the ping is printed in real-time, but I also get a PHP diagnostic error and callstack at the top of my page that says:
Notice: ob_end_flush() [ref.outcontrol]: failed to delete and flush buffer. No buffer to delete or flush in index.php on line 3
What do I need to do to either correct or suppress this error?
Update
If I change ob_end_flush() to $a = 1/0; I get a similar error and the output is realtime in all browsers. Is it something about the way the exception is printed that causes this to work?
some web browsers buffer the first x bytes before they start to render a page, under certain conditions.
try just outputting lots of whitespace first
I have a solution that works, but it is non-performant and icky. I throw an exception, but hide the exception dialog.
<?php
ob_implicit_flush(true);
// Something about the way exceptions are thrown causes Firefox and Chrome
// to be able to display the results of the system call in real-time rather
// than having to wait for the call to complete. So, I just hide the
// exception message. IE9 works with or without this.
echo "<div style=\"display:none\">";
$a = 1/0;
echo "</div>";
echo "<pre>";
system('ping -n 5 www.google.com');
echo "</pre>";
?>
To auto-scroll to the bottom of the page, I add some javascript:
<html><head>
<script language="javascript">
var int = self.setInterval("window.scrollBy(0,1000);", 200);
</script>
</head>
<body>
<?php
// insert above php code here
// stop scrolling when the execution finishes
echo '<script language="javascript">int = window.clearInterval(int);</script>';
?>
</body>
</html>
EDIT
#Chris's answer shows a much better solution.
echo '<div style="display:none">';
for ($a = 0; $a < 768; $a++)
echo ' ';
echo '</div>';
Just add this to flush the buffer:
if (eregi("chrome",$_SERVER['HTTP_USER_AGENT'])) {
echo "<div style=\"display:none\">";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo " ";
echo "</div>";
}
It has to be inside the loop. or between two output you need to show in real-time.
AND here's the shorthand trick:
add this:
if (eregi("chrome",$_SERVER['HTTP_USER_AGENT'])) {
echo "<div style=\"display:none\"></div>";
}
ob_end_flush() flushes the php output buffer, and requires an active output buffer created with ob_start().
I think you just want to call flush() to send the data to the client.
<?php
ob_implicit_flush(true);
flush();
system('ping -n 10 www.google.com');
?>
In your code, the error is pretty easy to interpret.
You call ob_end_flush() on line 3, but (like the error says), there is no output to flush. In essence, line 3 is useless because no output has been sent, so deleting the line will fix the error. If this is incorporated into a larger file, you might need to keep ob_end_flush() because some output may already have been captured.
EDIT: Since you need to flush it, either:
a: add ob_start(); to the top of the file.
b: replace ob_end_flush(); with flush();
EDIT2: Since the first didn't seem to work, this is the best I can offer: How to echo output in real time, (before script finishes)?

Categories