PHP » PYTHON |
login |
register |
about
|
PYTHON file_get_contents
is this article helpful?
|
Python replacement for PHP's file_get_contents
[
edit
| history
]
For offline files:
open(filename).read(1000) # ALWAYS specify a max size (in bytes). See [url]http://sebsauvage.net/python/snyppets/#bound_read[/url] For online files (e.g webpage): # Python 2 import urllib2 urllib2.urlopen(url).read(1000) # Python 3 import urllib.request urllib.request.urlopen(url).read(1000) #Python 2 function import urllib2 def file_get_contents(filename, use_include_path = 0, context = None, offset = -1, maxlen = -1): if (filename.find('://') > 0): ret = urllib2.urlopen(filename).read() if (offset > 0): ret = ret[offset:] if (maxlen > 0): ret = ret[:maxlen] return ret else: fp = open(filename,'rb') try: if (offset > 0): fp.seek(offset) ret = fp.read(maxlen) return ret finally: fp.close( ) file_get_contents(PHP 4 >= 4.3.0, PHP 5) file_get_contents — Reads entire file into a string Description
string file_get_contents
( string $filename
[, int $flags= 0
[, resource $context
[, int $offset= -1
[, int $maxlen= -1
]]]] )
This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE. file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
Parameters
Return ValuesThe function returns the read data or FALSE on failure. Examples
Example #1 Get and output the source of the homepage of a website
<?php
Example #2 Searching within the include_path
<?php
Example #3 Reading a section of a file
<?php The above example will output something similar to: string(14) "lle Bjori Ro"
Example #4 Using stream contexts
<?php
Changelog
Notes
Tip
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename and List of Supported Protocols/Wrappers for a list of supported URL protocols. Warning
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning. See Also
|
more
Recently updated
more
Most requested
more
Last requests
|