In Python you can parse an .ini file and access the single values like this:
myini.ini
[STRINGS]
mystring = fooooo
value = foo_bar
script.py
import configparser
config = configparser.ConfigParser()
# ----------------------------------------------------------------------
config.read("myini.ini")
test = config["STRINGS"]["mystring"]
print (test) #-> OUTPUT: fooooo
How can I do the same in PHP? Unfortunately, I was not able to find any examples.
Not to fear, parsing an .ini file is a standard method. (See parse_ini_file in the php docs).
Using your file as the base of this example:
myini.ini
[STRINGS]
mystring = fooooo
value = foo_bar
test.php
$ini_array = parse_ini_file("myini.ini");
print_r($ini_array); # prints the entire parsed .ini file
print($ini_array['mystring']); #prints "fooooo"
Note that by default parse_ini_file ignores sections and gloms all ini settings into the same object. If you'd like to have things scoped sectionally as in your python example, pass true for the process_sections parameter (second parameter).
test2.php
$ini_array = parse_ini_file("myini.ini", true /* will scope sectionally */);
print($ini_array['mystring']); #prints nothing
print($ini_array['STRINGS']['mystring']); #prints fooooo
From the intermediate approach, to get match section, it needs to read any INI file from line to line, in this case you can use fgets function or stream_get_line function to read for each line until the section founded or end of file (not founded).
Inside every line we can use preg_match (using regex pattern) that match with the actual section name been searched.
The essential of this approach is to reduce memory usage meanwhile many concurrent request occurs at the same time, so in this case we use string object with any sufficient length as a buffer.
Good luck Buddy.
Related
Situation.
I download and process multiple xml files. Download the first file.
Open it with $xml_file = simplexml_load_file( dirname(__FILE__). '/_downloaded_files/filename.xml' );
Go through the file, create variables to insert into mysql, insert into mysql. Do the same with next xml files.
After i processed the opened xml file, i unset (set null) variables. Like $xml_file = null; Tried also like unset($xml_file);, saw no difference. Somewhere found advice to use gc_enable(); gc_collect_cycles();, also no difference (no effect).
After executed mysql code, also set to null all used variables.
As result with echo '<pre>', print_r(get_defined_vars(), true), '</pre>'; saw like
[one_variable] =>
[another_variable] => 1
I saw many (~ 100) variables with empty content (or one short value for the a variable).
But with echo (memory_get_peak_usage(false)/1024/1024); see 38.01180267334 MiB memory used.
Can someone advice where is problem? ~100 empty variables can not use 38 megabytes... What else may use the memory?
I'm looking to read contents of a file between two tags in a large text file (so can't read the whole file at once due to memory restrictions on my server provider). This file has around 500000 lines of text.
This ( PHP: Read Specific Line From File ) isn't an option (I don't think), as the text I need to read varies in length and will take up multiple lines (varies from 20-5000 lines).
I am planning to use fopen, fread (read only) and fclose to read the file contents. I have experience of using these functions already.
I am looking to read all the contents in a selected part of the file. i.e.
File contents example
<<TAGNAME-1>>AAAA AAAA AAAA<<//TAGNAME-1>>
<<TAGNAME-2>>TEXT TEXT TEXT<<//TAGNAME-2>>
To select the text "AAAA AAAA AAAA" between the <<TAGNAME-1>> and <<//TAGNAME-1>> when TAGNAME-1 is called as a variable in my script.
How could I go about selecting all the text between the two tags that I require? (and ignore the remainder of the file) I have the ability to create the two tags where required in my php script - my issue is implementing this within the fread function.
You could grep the text file which would only return the text with a matching tag.
$tagnum = 2; //variable
$pattern = "<<TAGNAME-";
$searchstr = $pattern.$tagnum; //concat the prefix with the tag number
$fpath ="testtext.txt"; //define path to text file
$result = exec('grep -in "'.$searchstr.'" '.$fpath);
echo $result;
Where $tagnum would define each tag to search. I've tested it in my sandbox and it works as expected. Note this will read the whole line until the end tad or newline is reached.
Regards,
I have a huge XML file (114 KB/1719 lines; see the error message below why I say huge) and I try to read it as I have done with two similar files before.
The other two files load normally and are of comparable size the only difference being that the file in question contains Arabic text. So here is the PHP code:
$doc3 = new DOMDocument('1.0', 'utf-8');
$doc3->load($masternumber.'.xml');
And the error is:
Warning: DOMDocument::load() [domdocument.load]: Excessive depth in document: 256 use XML_PARSE_HUGE option in file: ...
Then $doc3 doesn't load the file. So I modified the code:
$doc3->load($masternumber.'.xml', "LIBXML_PARSEHUGE");
And I end-up with another warrning:
Warning: DOMDocument::load() expects parameter 2 to be long, string given in...
$doc3 is empty again.
What is wrong with it? The other files contain the same text in other languages and load properly but not this one? I am using PHP 5.3.9.
Use a constant, not a string.
$doc3->load($masternumber.'.xml', LIBXML_PARSEHUGE);
See the DOMDocument::load() documentation for complete details. The second parameter is a long integer representing the selected options from the list of constants.
Incidentally, if you need multiple options for any reason, it is done by combining them with the bitwise OR operator |
// Multiple options OR'd together...
// Just FYI, not specific to your situation...
$doc3->load($masternumber.'.xml', LIBXML_PARSEHUGE|LIBXML_NSCLEAN);
Is there a function where I'm not constrained to open a file to write in it and then to close it up. I'm searching for one function looking like this
bool thefunction(string line, string path, string mode);
line is what I want to write in the file located from path and either from the end of the document or at the start erasing all the content defined with mode argument.
Ok this sounds a bit picky, but it's the idea. I want to make a count up and need a file to increment the value in it.
Look into file_put_contents(). You'll still need to chmod() the file if you require different permissions than file_put_contents() creates.
Example:
// This writes a line to a file, appending to what's already there
$success = file_put_contents("/path/to/file.txt", "This string goes into the file\n", FILE_APPEND);
I have a file named "connection.php". I want to read the contents of this file to a string. I use fopen, and read functions for reading. But when I am reading I just got only last 2-3 lines on that file. That means no PHP scripts can read like echo, functions etc. How can I read the whole contents on that file?
<?php
$str = file_get_contents('connection.php');
var_dump($str);
?>
note that if 'connection.php' contains '<?php' at the beginning, and you try to output it to a browser, you likely won't see anything unless you perform a "View Source".
Quoting the manual page of fread :
fread() reads up to length bytes from
the file pointer referenced by handle
. Reading stops as soon as one of the
following conditions is met:
length bytes have been read
EOF (end of file) is reached
a packet becomes available (for network streams)
8192 bytes have been read (after opening userspace stream)
If you want to read a whole file, you'll need to use some kind of loop, to read data until you reach the end of the file.
Or, as an alternate (probably easier), you can use file_get_contents, which will get you the whole content of the file with only one function call.
Which means no need for fopen + multiple fread + fclose ;-)
Perhaps your browser is hiding the content because it starts with '<?php'. You can try View Source in your web browser, or echo the contents in the following way:
<?php
$contents = file_get_contents('connection.php');
echo "<pre>";
echo htmlentities($contents);
echo "</pre>";