字符串函数
在线手册:中文 英文
PHP手册

print

(PHP 4, PHP 5)

print输出字符串

说明

int print ( string $arg )

输出 arg

print() 实际上不是一个函数(它是一个语言结构),因此你可以不必使用圆括号来括起它的参数列表。

参数

arg

输入数据。

返回值

总是返回 1

范例

Example #1 print() 范例

<?php
print("Hello World");

print 
"print() also works without parentheses.";

print 
"This spans
multiple lines. The newlines will be
output as well"
;

print 
"This spans\nmultiple lines. The newlines will be\noutput as well.";

print 
"escaping characters is done \"Like this\".";

// 可以在打印语句中使用变量
$foo "foobar";
$bar "barbaz";

print 
"foo is $foo"// foo is foobar

// 也可以使用数组
$bar = array("value" => "foo");

print 
"this is {$bar['value']} !"// this is foo !

// 使用单引号将打印变量名,而不是变量的值
print 'foo is $foo'// foo is $foo

// 如果没有使用任何其他字符,可以仅打印变量
print $foo;          // foobar

print <<<END
This uses the "here document" syntax to output
multiple lines with 
$variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
?>

注释

Note: 因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

参见


字符串函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 输出字符串

用户评论:

aflavio at gmail dot com (12-Jan-2011 08:32)

Check this statement:

echo 3 . print(2) . print(4) . 5 . 'c' . print(6) . print(7). 'b' .print(8) . 'a';

It's will always output starting from the right to the left.

Thus we have:

8a                              //1o print
7b18a                        //2o print
617b18a                    //3o print
8a7b16145c1             //4o print

8a7b16145c12131     //Final output

That's it.

sdaau (22-Dec-2009 10:28)

Printing an empty string from PHP, as in

print "";

returns a single byte (content length=1) - the line-feed character '\n' (0a).

So if you truly want to return an empty string, you may want to use "flush()" instead - then headers without any Content-length will be returned.

Do note, however, that regardless of whether print or flush is used, accessing such a PHP output from AJAX (via .responseText) will always have a '\n' as a value for an "empty" string sent from PHP.

Chris Watson (01-Oct-2009 09:20)

mvpetrovich of 2007 could just use single quotes as his string delimiters (see the example in the current documentation).
It's not ALWAYS appropriate, but generally it is best (the Zend Framework coding standards have a good take on this). It yields a number of interesting benefits:
1: Nobody will be tempted to write functions to replace backticks or other characters with double quotes. Such functions may cause a (negligible) loss of efficiency, and maybe other undesired effects.
2: You will be able to use double quotes without escaping. This is recommended (although not required) for HTML and XML attributes, as well as quoted text.
3: The script will hit the browser very slightly slightly faster since PHP doesn't have to scan through the string looking for variables, escaped characters, curly braces or other things.
4: Your code gets ten times easier to read. (as mvpetrovich pointed out)

If, in spite of these four excellent benefits, you really MUST still use double quotes to delimit boring old string constants (and seriously, why would you?), you could use the slightly less favourable single quotes as delimiters for most markup languages.
HTML served as HTML will even let you lay out unquoted attributes (yuck).

It should also be noted though that if you are just printing bare strings, you may as well shut off the php parser. The quickest way to send a string is to write it as plain text, OUTSIDE of the php tags. This will also make your code look excellent in a lot of syntax highlighters.

There are few disadvantages to doing this, if any. Output buffering still works. All your classes and objects and includes remain in place. Your script runs faster. World peace is obtained.

http://www.danielxmorris.com (28-Aug-2008 03:46)

An update to the println function I wrote below, this is a more efficient, correct and returns a value (1, always; (print)).

<?php

   
function println($string_message = '') {
        return isset(
$_SERVER['SERVER_PROTOCOL']) ? print "$string_message<br />" . PHP_EOL:
          print
$string_message . PHP_EOL;
    }

?>

user at example dot net (25-Aug-2008 05:47)

Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.

Most would expect the following behavior:
<?php
   
if (print("foo") && print("bar")) {
       
// "foo" and "bar" have been printed
   
}
?>

But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is

    ("foo") && print("bar")

and the argument of the second print is just

    ("bar")

For the expected behavior of the first example, you need to write:
<?php
   
if ((print "foo") && (print "bar")) {
       
// "foo" and "bar" have been printed
   
}
?>

user at example dot net (25-Aug-2008 05:45)

Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.

Most would expect the following behavior:
<?php
   
if (print("foo") && print("bar")) {
       
// "foo" and "bar" had been printed
   
}
?>

But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is

    ("foo") && print("bar")

and the argument of the second print is just

    ("bar")

For the expected behavior of the first example, you need to write:
<?php
   
if ((print "foo") && (print "bar")) {
       
// "foo" and "bar" had been printed
   
}
?>

danielxmorris @ gmail dotcom (16-May-2008 12:08)

I wrote a println function that determines whether a \n or a <br /> should be appended to the line depending on whether it's being executed in a shell or a browser window.  People have probably thought of this before but I thought I'd post it anyway - it may help a couple of people.

<?php
function println ($string_message) {
   
$_SERVER['SERVER_PROTOCOL'] ? print "$string_message<br />" : print "$string_message\n";
}
?>

Examples:

Running in a browser:

<?php println ("Hello, world!"); ?>
Output: Hello, world!<br />

Running in a shell:

<?php println ("Hello, world!"); ?>
Output: Hello, world!\n

jon (01-Jun-2007 03:19)

the FAQTs article can be found archived at http://web.archive.org/web/20060601063513/http
://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

(url split to get past the line-length limitation)

mvpetrovich (30-Mar-2007 07:02)

I grew quite tired of backslashes, and wrote these routines. It uses the back single quote as a substitute for double quotes within a statement.  It made my code much more readable.  It is a little easier than using a "here document."  I also found I make a few less typing errors.

<?php

function qq($text) {return str_replace('`','"',$text); }
function
printq($text) { print qq($text); }
function
printqn($text) { print qq($text)."\n"; }

//example - before

echo "<a href=\"#\" class=\"stdbutton\" style=\"float:left;\" onclick=\"myfunction(); return false;\">My Link</a>\n";

//becomes - with printqn function

printqn("<a href=`#` class=`stdbutton` style=`float:left;` onclick=`myfunction(); return false;`>My Link</a>");

?>

floppie at quadra-tec dot net (15-Nov-2006 05:09)

At the top of your page, do something to this effect:
<?php
    $n
= "\n";
   
$t = "\t";
?>

Then, if you need your table cell four tabs in:

<?php echo($t . $t . $t . $t . '<td>whatever</td>' . $n); ?>

This means the parser only has to interpret four characters inside double quotes, then just stores them in variables.  With strings that small, concatenating six things together won't be slow at all.

vincent at bevort dot com (21-May-2006 08:36)

Sometime there is no choice in using a single or double quote
ie when using special chars to format the output to make the HTML more readable you have to use the Double qoutes. Single quotes make PHP fotmat the '\n' as text

phpnet at i3x171um dot com (21-May-2006 03:41)

I have written a script to benchmark the several methods of outputting data in PHP: via single quotes, double quotes, heredoc, and printf. The script constructs a paragraph of text with each method. It performs this construction 10,000 times, then records how long it took. In total, it prints 160,000 times and records 16 timings. Here are the raw results.

Outputted straight to browser--

Single quotes: 2,813 ms
...with concatenation: 1,179 ms
Double quotes: 5,180 ms
...with concatenation: 3,937 ms
heredoc: 7,300 ms
...with concatenation: 6,288 ms
printf: 9,527 ms
...with concatenation: 8,564 ms

Outputted to the output buffer--

Single quotes: 8 ms
...with concatenation: 38 ms
Double quotes: 8 ms
...with concatenation: 47 ms
heredoc: 17 ms
...with concatenation: 49 ms
printf: 54 ms
...with concatenation: 52 ms

A nice graph of the script's output can be found here:
http://i3x171um.com/output_benchmarks/ob.gif

So what should you choose to print your text? I found several things out writing this.

First, it should be noted that the print and echo keywords are interchangeable, performance-wise. The timings show that one is probably an alias for the other. So use whichever you feel most comfortable with.

Second, if you've ever wondered which was better, the definitive answer is single quotes. Single quotes are at least four times faster in any situation. Double quotes, while more convenient, do pose a debatably significant performance issue when outputting massive amounts of data.

Third, stay away from heredoc, and absolutely stay away from [s]printf. They're slow, and the alternatives are there.

The source of my script can be found here:
http://i3x171um.com/output_benchmarks/ob.txt

DO NOT RUN THE SCRIPT ON THE INTERNET! Run it instead from localhost. The script outputs ~45 megabytes of text in an html comment at the top of the page by default. Expect the benchmark to take ~45 seconds. If this is too long, you can change the amount of iterations to a lower number (the results scale accurately down to about 1,000 iterations).

g8z at yahoo dot com (14-Mar-2006 07:16)

I wanted to print a file on a Windows 2003 server from PHP, and found the "print" function instead. Just in case some other users are trying to physically print to a printer, rather than print to the screen, here's a function to do it.

This function will print a single file of one of these types: pdf, doc, xls, rtf, or plain text. If you have the full .exe path, you can print other document types, too. The shell_exec function is not enabled in safe mode.

Courtesy of Darren's Script Archive: http://www.tufat.com

<?php

function print_file($filename)
{
   
// path to your adobe executable
   
$adobe_path='"C:/Program Files/Adobe/Acrobat 7.0/Reader/AcroRd32.exe"';

   
$ext='';
   
$ext=strrchr($filename,'.');
   
$ext=substr($ext,1);
   
$ext_xl=substr($ext,0,2);

    if (
$ext=='pdf') {
       
shell_exec ($adobe_path.' /t '.$filename);
    }
    else if (
$ext=='doc'||$ext=='rtf'||$ext=='txt') {
       
$word = new COM("Word.Application");
       
$word->visible = true;
       
$word->Documents->Open($filename);
       
$word->ActiveDocument->PrintOut();
       
$word->ActiveDocument->Close();
       
$word->Quit();
    }
    else if (
$ext_xl=='xl') {
       
$excel = new COM("Excel.Application");
       
$excel->visible = true;
       
$excel->Workbooks->Open($filename);
       
$excel->ActiveWorkBook->PrintOut();
       
$excel->ActiveWorkBook->Close();
       
$excel->Quit();
    }
}

// example of printing a PDF

print_file("C:/photo_gallery.pdf");

?>

jon at tap dot net (05-Dec-2005 09:48)

I have a small utility run from the command line that processes a potentially huge list of files. As it can take hours to complete, I stuck a 

print '.';

statement in the body of the main loop to prove that something was  happening.

For reasons unknown to me, the utiliity suddenly started buffering the output such that it printed nothing until completion, defeating the purpose of the running monitor. Adding flush() statements did nothing. The problem was solved by using

fputs(STDOUT, '.');

but I have no idea why.

james-web at and dot org (25-Jul-2005 11:47)

Note that if you want to dump the value of a variable, you want to use print_r(), var_dump() or var_export().

ejallison at gmail dot com (16-Jul-2005 11:10)

This is a simple function for printing debug comments that I didn't think of for a long time. Maybe it'll serve you good too.

<?php

function printd($str) {
  if (
$debug) { echo $str; }
}

// ...

if ($valueCalculatedEarlierInTheScript == 3) {
 
doSomethingWithNoOutput();
 
printd("doSomethingWithNoOutput() has executed.");
}

?>

It's mostly just to make sure everything is running without having to go through everything and put in echo "Step #whatever has executed" whenever something mysterious isn't working.

gem at rellim dot com (05-Nov-2004 09:28)

HERE Documents can reference arrays as long as you enclose
the vars in {}.

Like this:

<?php

$line
= array( 'title' => "Hello", 'date' => 'Today');

echo <<<EOT
Title: {$line['title']}
Date:
{$line['date']}
EOT;

?>

Run this and get
Title: Hello
Date: Today

More info here, scroll down to "heredoc syntax":
http://www.php.net/manual/en/language.types.string.php

rjl at xs4all dot nl (16-Jan-2004 12:08)

To elaborate on above example adding an
array variable
$text = <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
User = {$_REQUEST['user']}
END;

'print $text;' Will output the string. Very handy for storing HTML.
Or adding {} around the array will allow you to use
above mentioned html blocks in conjuction with forms.

Rene =<>=