PHP/File Directory/file get contents — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:04, 26 мая 2010
Содержание
- 1 Checking for an error from file_get_contents()
- 2 Check net speed by loading a file
- 3 Fetching a URL with file_get_contents()
- 4 file_get_contents.php
- 5 file_put_contents( ) writes to a file with the equivalent of fopen( ), fwrite( ), and fclose( ) all in one function, just like file_get_contents( ).
- 6 Reading a file into a string
- 7 Retrieving a protected page
- 8 Retrieving a remote page with file_get_contents()
- 9 Use file_get_contents with a URL
Checking for an error from file_get_contents()
$page = file_get_contents("page-template.html");
if ($page === false) {
print "Couldn"t load template: $php_errormsg";
} else {
// ... process template here
}
//page-template.html
<html>
<head><title>{page_title}</title></head>
<body bgcolor="{color}">
<h1>Hello, {name}</h1>
</body>
</html>
Check net speed by loading a file
<?php
$data = file_get_contents("data.txt");
$fsize = filesize("textfile.txt") / 1024;
$start = time();
$stop = time();
$duration = $stop - $start;
$speed = round($fsize / $duration,2);
echo "Your network speed: $speed KB/sec.";
?>
Fetching a URL with file_get_contents()
<?php
$page = file_get_contents("http://www.example.ru/robots.txt");
?>
file_get_contents.php
<?php
$userfile= file_get_contents("data.txt");
$users = explode("\n",$userfile);
foreach ($users as $user) {
list($name, $email) = explode(" ", $user);
echo "<a href=\"mailto:$email\">$name/a> <br />";
}
?>
file_put_contents( ) writes to a file with the equivalent of fopen( ), fwrite( ), and fclose( ) all in one function, just like file_get_contents( ).
<?
$filename = "data.txt";
$myarray[ ] = "This is line one";
$myarray[ ] = "This is line two";
$myarray[ ] = "This is line three";
$mystring = implode("\n", $myarray);
$numbytes = file_put_contents($filename, $mystring);
print "$numbytes bytes written\n";
?>
Reading a file into a string
<?php
$people = file_get_contents("people.txt");
if (preg_match("/Names:.*(David|Susannah)/i",$people)) {
print "people.txt matches.";
}
?>
Retrieving a protected page
<?php
$url = "http://tom:password@www.example.ru/secrets.php";
$page = file_get_contents($url);
?>
Retrieving a remote page with file_get_contents()
<?
$zip = 98052;
$weather_page = file_get_contents("http://www.demo.ru/z.php?inputstring=" . $zip);
$page = strstr($weather_page,"Detailed Forecast");
$table_start = strpos($page, "<table");
$table_end = strpos($page, "</table>") + 8;
print substr($page, $table_start, $table_end - $table_start);
?>
Use file_get_contents with a URL
<?
$url = "http://www.demo.ru/";
$page = file_get_contents($url);
if (preg_match_all("@<a href="[^"]+">.+?</a>@", $page, $matches)) {
foreach ($matches[0] as $link) {
print "$link <br/>\n";
}
}
?>