PHP reading array from txt file not working [closed] - php

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!

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))

PHP Unserialize data for use in array - sub standard characters in string

I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517

How to translate txt file settings into php array

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.

Make array from array values and save it to a file

I am working on a project in which I will get an array.
When I use print_r($arr) it looks like this:
Array
(
[0] => games,
[1] => wallpapers,
.....
)
What i want to do is that i want it's value to be in an array like array('games','wallpapers') and save it to a file called data.txt using file_put_contents.
I did it once myown using implode() but sometimes it gets error. Is there a good way?
You need to serialize it and save it to a file. You can do it as a comma-separated values using implode(), or as a json string using json_encode() or using serialize(). All three of those links have excellent documentation and examples.
If you still have troubles, please edit your question with more specific details and the code you've worked on so far.
Try this,
<?php
$a=array
(
0 => 'games',
1 => 'wallpapers'
);
$str= implode(',',$a);
file_put_contents('data.txt', $str);
?>
data.txt
games,wallpapers
To retrieve the values, use array_values(). To store this array to disk, first serialize(), then store the output anyway you like - file_put_contents is the simplest way I believe.

build SQL statement from json encoded string php

Welcome Stackoverflow nation ! I'm trying to decode json encoded string into SQL statement withing php.
Lets say I've such a json encoded string =>
$j = '{"groupOp":"AND","rules":[{"field":"id","op":"cn","data":"A"},{"field":"i_name","op":"cn","data":"B"}]}';
I want to build SQL WHERE clause (needed for filterToolbar search in jqGrid), something like this => "WHERE id LIKE %A% AND i_name LIKE %B% " and etc.
I've done this =>
$d = json_decode($j);
$filterArray = get_object_vars($d); // makes array
foreach($filterArray as $m_arr_name => $m_arr_key){
// here I can't made up my mind how to continue build SQL statement which I've mentioned above
}
Any ideas how to do that , thanks preliminarily :)
The first problem is you will want to pull out the groupOp operator.
Then, you have an object and inside that you have an array of objects, so you may want to look at the results of filterArray as that won't have the value you want.
Then, when you loop through, you will want to do it with an index so you can just pull the values out in order.
You may want to look at this question to see how you can get data out of the array:
json decode in php
And here is another question that may be helpful for you:
How to decode a JSON String with several objects in PHP?
There is an answer with an implementation for the server-side php code here
Correction: I had to unescape double-quotes in the 'filters' parameter to get it working:
$filters = str_replace('\"','"' ,$_POST['filters']);

Categories