Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

print

(PHP 3, PHP 4, PHP 5)

print -- Выводит строку

Description

int print ( string arg )

Выводит arg. Всегда возвращает 1.

print() не является "настоящей" функцией (это конструкция языка) поэтому заключать аргумент в скобки не обязательно.

Пример 1. Примеры использования print()

<?php
print ("Привет мир!");

print
"print() можно использовать и без скобок.";

print
"Это занимет
несколько строк. Переводы строки тоже
выводятся"
;

print
"Это занимет\nнесколько строк. Переводы строки тоже\nвыводятся";

print
"Экранирование символов делается \"Так\".";

// с print можно использовать переменные ...
$foo = "foobar";
$bar = "barbaz";

print
"foo - это $foo"; // foo - это foobar

// ... и массивы
$bar = array("value" => "foo");

print
"это {$bar['value']} !"; // это foo !

// При использовании одиночных кавычек выводится
// имя переменной,а не значение
print 'foo - это $foo'; // foo - это $foo

// можно вывести просто значения переменных
print $foo;          // foobar
print $foo,$bar;     // foobarbarbaz

print <<<END
Здесь используется синтаксис "here document" для вывода
нескольких строк с подстановкой переменных $variable.
Заметьте,что закрывающий идентификатор должен
располагаться в отдельной строке. никаких пробелов!
END;
?>

Различия между print() и echo() рассматриваются в этой статье: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций

См. также описания функций echo(), printf() и flush().



printf> <parse_str
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
print
jon
01-Jun-2007 07: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 12: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 09: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 12: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
20-May-2006 07: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
13-Mar-2006 11: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");

?>
hw{
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Z058440144362 Z348613067571