How to translate txt file settings into php array - php

I have text file containing values like this:
varname:
{
varname2: value
varname3:
{
varname4: value
}
}
I need to get this somehow into php array like this:
array(
varname => array
(
varname2 => value
varname3 => array
(
varname4 => value
)
)
)
How can i do this?
I have tried looping through file and trying to make values like that but it gets very tricky when there is multiple level array. Spent many hours without luck...

I suggest you (if you can) to change your file format to a JSON format, that is very similar to your format now:
{"varname":{"varname2":"value","varname3":{"varname4":"value"}}}
Then you can read the file and use json_decode to obtain the array in a very simple form. Here I write the code for decode json to array and echo it:
$s = file_get_contents('datos.js');
$ar = json_decode($s, true);
print_r($ar);

It depends on how much of a hack you want it to be. If you have a true defined format and want to be strict you'd start with a lexer. See http://wezfurlong.org/blog/2006/nov/parser-and-lexer-generators-for-php/ or https://github.com/nikic/Phlexy
On the other hand you could also make it in two steps (depending on how complicated the now shown use cases are).
Replace all leading spaces and replace : \n{ with : { for easier parsing.
Write a recursive parsing function. In every line everything before : is the variable name, everything after the value. If the value is { to a recursion until } and use the result as the value.

Related

I need to change the php code in the file so instead of the current json output

So i am using this PHP code to create the json output, and I am having an issue where it’s creating an array of array with the info. I would like to get rid of one array and just display the list of API’s thats been used and number that has been used.
Looks as though the difference is you have...
"apis":[{"item_search":"0\n"},{"item_recommended":"0\n"}]
and want
"apis":{"item_search":"0\n","item_recommended":"0\n"}
If this is the case, you need to change the way you build the data from just adding new objects each time to setting the key values directly in the array...
$zone_1 = [];
foreach($zone_1_apis as $api_name ) {
$zone_1[substr($api_name, 0,-5)] = file_get_contents('keys/'.$_GET['key'].'/zone_1/'.$api_name);
}
You also need to do the same for $zone_2 as well.
It may also be good to use trim() round some of the values as they also seem to contain \n characters, so perhaps...
trim(file_get_contents('keys/'.$_GET['key'].'/zone_1/'.$api_name))

associative array overwriting entries php

I am trying to build an associative array to save the following information. A url, a word, and a frequency (# of occurrences of that word on that webpage).
I want to be able to access the information where I enter a string for the url and word and receive the frequency, like this:
$test["somewhere.com"]["biology"] => 5
$test["somewhere.com"]["auto"] => 10
$test["elsewhere.com"]["biology"] => 7
Right now I am pulling the information out of a db one row at a time and am trying the following:
$test["$url"] = array("$word" => "$freq");
After every iteration it gets over written. How do I change the syntax to avoid this situation? Is it possible to build the structure I want?
Thanks.
EDIT:
I was assigning values to array in a while loop. I made the mistake of initializing the array within the loop. I wasn't overwriting entries, I was
re-initializing the array unintentionally. That was my problem.
You are reassigning $test["$url"] as a new array each time. Use the full path:
$test[$url][$word] = $freq;
Also, no need for the quotes.
Instead of overwriting the first level contents, declare a new property for it. (without knowing how are you getting your urls, words and frequencies, the following is just an example)
$test = []
foreach($urls as $url => $words) {
$test[$url]=[];
foreach( $words as $word => $freq) {
$test[$url][$word] = $freq;
}
}
However, this looks awfully like trying to build an associative array that's already built.

Getting value from string by index

I have a string of data formatted like so:
[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]
The string doesn't have any index/numbers like a regular array would and I'm finding it difficult to extract individual values e.g. with a regular array I could use:
$string[0]["pr_a_w"]
To get the first instance of "pr_a_w" and I could use:
$string[1]["pr_a_w"]
To get the second instance etc.
Is it possible to get single values from this string based on their number?
What you have there is valid JSON (serialized array of objects), so you could use json_decode to translate the serialized data into a native PHP array:
$array = json_decode('[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]',true);
$array will then allow you to do exactly what you stated you'd like to do above.
$array[0]["pr_a_w"]; // will give you 10
$array[1]["pr_a_w"]; // will give you 10
Try like this, No need to access with array index. You will get error if you access wrong index.
$json_arr= json_decode('[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]',true);
foreach($json_arr as $row){
echo $row['pr_a_w']."<br>";
}

PHP reading array from txt file not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Im not sure what I am doing wrong here. I have a txt file that stores and array:
Array
(
[0] => Array
(
[sku] => 123123
)
)
When I go to read the file by php and loop over it, it gives me this error:
Invalid argument supplied for foreach()
Code:
$items = $file->getContents();
foreach($items as $item){
}
Alternate Code (serialize and unserialize):
$items = $file->getContents();
$itemsA = serialize($items);
$itemsB = unserialize($itemsA);
foreach($itemsB as $item){
}
Produces this error as well: Invalid argument supplied for foreach()
you can serialize it then unserialize or json_encode then json_decode
if your files are not dynamic (aka config files) check this answer
That is a var_dumped array. To store an array in a file you can serialize it and then write it and when you read it from the file you then unserialize it to get the array back.
Array
(
[0] => Array
(
[sku] => 123123
)
)
$items = $file->getContents();
$items = str_replace(array('> Array','[',']'),array('> new Array',"'","'"),$items );
file_put_content("TMPFILENAME","<\?PHP\n return new $items;");
$items = include "TMPFILENAME";
Replace " ' if needed
If you need numeric key do some like first:
$items = preg_replace('#(?:\[([0-9]+)\])+#','$1',$items );
Still dirty!
Convert var_dump of array back to array variable
\? to ? !!! WYSIWYG...
Due to the lack of code, I will make a few assumptions.
These will be changed when the needed code is added.
There is no information about how that file was created.
The output looks like it came from either var_dump() or print_r().
I'm not entirely sure of which was used.
If these were used, forget the file.
If you want to recover this file, you have to manually convert it into actual working code (by adding quotes around the key names in the arrays), add return (with space after) to the file and include it.
To re-do the file, and for the next time you write it, you have several methods:
Use the function serialize():
This is easy to use!
Simply pass the variables and you are set.
Here's an example:
$text=serialize($variable);
Then you use unserialize() to extract the data.
Like this:
$data=unserialize($text);
Use json_encode() to save the data.
It works the same way:
$text=json_encode($data);
And use json_decode() to get the data back, like this:
$data=json_decode($text);
Notice that the JSON data can be used in many other languages, including Javascript!
Also, this method is faster than serialize().
Use var_export() to get valid PHP code in a string.
Like this:
$php=var_export($data);
//write the file like this, prepending '<?php return ' to it:
file_put_contents('file.php','<?php return '.$php);
Which will write something like:
return Array(1,2,3); //example code.
To read the file, simply use include or require:
$data=include 'file.php';
Yes, include can receive the array data!
This is, by far, the fastest method!

outputting all array values to file with php

Im working with a foreign API and im trying to get a fix on what all its sending to my file with the GET method.
How can i output something like print_r($_GET) to a file so i can read what all its sending?
If you have a hash, both of the listen solutions won't give you the keys. So here's a way to get your output formatted by print_r:
$var = print_r($your_array, 1);
file_put_contents("your_file.txt",$var);
The second option of print_r is boolean, and when set to true, captures the output.
It sounds like you need a log to store the $_GET variables being submitted to your script, for debug purposes. I'd do something like this appending values to the end of the file, so the file is not overwritten every request:
file_put_contents('path_to_log.txt', print_r($_GET, true), FILE_APPEND);
Writing to a file:
You could use file_put_contents() to create the file with your output. This function will accept a string, or an array, which releases you of the burden to convert your array into a writable-format.
file_put_contents("myget.txt", $_GET);
As stated in the comments, this option isn't ideal for multidimensional arrays. However, the next solution is.
Maintaining format:
If you'd like to maintain the print_r() formatting, simply set the second parameter to true to return the value into a variable rather than outputting it immediately:
$output = print_r($_GET, true);
file_put_contents("myget.txt", $output);

Categories