Embedding PHP in Web Pages
|
57
XML Style
Because of the advent of the eXtensible Markup Language (XML) and the migration
of HTML to an XML language (XHTML), the currently preferred technique for
embedding PHP uses XML-compliant tags to denote PHP instructions.
Coming up with tags to demark PHP commands in XML was easy, because XML
allows the definition of new tags. To use this style, surround your PHP code with
and
?>
. Everything between these markers is interpreted as PHP, and everything
outside the markers is not. Although it is not necessary to include spaces between the
markers and the enclosed text, doing so improves readability. For example, to get
PHP to print “Hello, world”, you can insert the following line in a web page:
The trailing semicolon on the statement is optional, because the end of the block
also forces the end of the expression. Embedded in a complete HTML file, this looks
like:
This is my first PHP program!
Look, ma! It's my first PHP program:
How cool is that?
Look, ma! It's my first PHP program:
Hello, world!
How cool is that?
$now = strftime("%c");
if (!session_is_registered('l')) {
$l = new Log("/tmp/persistent_log");
session_register('l');
$l->write("Created $now");
echo("Created session and persistent log object.
");
}
$l->write("Viewed first page $now");
echo "The log contains:
";
echo nl2br($l->read( ));
?>
Move to the next page
$now = strftime("%c");
$l->write("Viewed page 2 at $now");
echo "The log contains:
";
echo nl2br($l->read( ));
?>
$word = $_POST['word'];
$number = $_POST['number'];
$chunks = ceil(strlen($word)/$number);
echo "The $number-letter chunks of '$word' are:
\n";
for ($i=0; $i < $chunks; $i++) {
$chunk = substr($word, $i*3, 3);
printf("%d: %s
\n", $i+1, $chunk);
}
?>
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
?>
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$fahr = $_POST['fahrenheit'];
$celsius = ($fahr - 32) * 5/9;
printf("%.2fF is %.2fC", $fahr, $celsius);
} else {
die("This script only works with GET and POST requests.");
}
?>
$fahr = $_GET['fahrenheit'];
if (is_null($fahr)) {
?>
} else {
$celsius = ($fahr - 32) * 5/9;
printf("%.2fF is %.2fC", $fahr, $celsius);
}
?>
,ch07.15968 Page 167 Wednesday, March 13, 2002 11:44 AM
This is the Title of the Book, eMatter Edition
Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
Do'stlaringiz bilan baham: |