Get arrays from a file then loop it - php

Try to get arrays from a file like...
data.txt
Array
(
[0] => 288
[1] => 287
[2] => 173
)
my.php
$data = file('data.txt');
foreach ($data as $id) {
echo $id." - ";
}
Why its echo all arrays back ? like data.txt
Why not echo like 288 - 287 - 173 ?
CLOSED : I using JSON now

When saving your data, get the string representation using serialize:
$str = serialize($arr);
You can then use unserialize to decode your array:
$arr = unserialize(file(data.txt));

Your method loads the data in data.txt as a string, and php will not parse it as code. Try
$data = eval(file(data.txt));
See more on eval here: PHP manual on eval
Also note that the syntax in data.txt is invalid. You want:
array(288, 287, 173);
PHP will automatically create the indexes as needed.
On a second note, this is probably not the best way to go about it. Not knowing what you aim to achieve here, but would it not be better to just have the array set in your php file?

Related

How to print specific json array values in php script?

I have a json array that looks like this:
{"server-host-01":{"API":"Good","JETS":"Good","HTTPD":"Good","DISK":"23% Used","CPU":"WARNING: Avg idle at: 98% "},"server-host-02":{"DISK":"18% Used","CPU":"Avg idle at: 99% "}}
I have a key then inside that key another array of key:values and then another key with the same setup of key:values inside.
In my php script i am assigning the json file to the variable of $files and then using json_decode to turn it into a php array (i think)
$files = (my_json_file.json);
$string = file_get_contents($file);
$json_a = json_decode($string, true);
Now i have the array in php i would like to print the main keys out and then print the key:values of the keys. They will be going into a html table but specially im looking for help printing out the values as i need them before i worry about the html part.
Viewing the JSON contents
You have a JSON encoded array which contains two arrays inside of it as below (which I obtained via this link):
array (
'server-host-01' =>
array (
'API' => 'Good',
'JETS' => 'Good',
'HTTPD' => 'Good',
'DISK' => '23% Used',
'CPU' => 'WARNING: Avg idle at: 98% ',
),
'server-host-02' =>
array (
'DISK' => '18% Used',
'CPU' => 'Avg idle at: 99% ',
),
)
If you wanted to view all values pertaining to server-host-01 you could do e.g.
var_dump($json_a['server-host-01']);
If you wanted only the CPU status you could to do e.g.
$server_host_01_CPU_Status = $json_a['server-host-01']['CPU'];
var_dump($server-host-01-CPU-Status);
Example code
Here's an example of the above in action:
<?php
$json = json_decode('{"server-host-01":{"API":"Good","JETS":"Good","HTTPD":"Good","DISK":"23% Used","CPU":"WARNING: Avg idle at: 98% "},"server-host-02":{"DISK":"18% Used","CPU":"Avg idle at: 99% "}}');
$server_host_01_CPU_Status = $json['server-host-01']['CPU'];
var_dump($server_host_01_CPU_Status);
foreach($json['server-host-02'] as $key => $value)
{
var_dump("$key = $value");
}
?>
Other notes
Your line $files = (my_json_file.json); is invalid PHP. I'm not 100% sure what you're trying to achieve but firstly:
1) my_json_file.json isn't wrapped in quotes so PHP is treating it as a constant variable rather than a string (and this throws an error too -- turn PHP server errors on to see it)
2) The unquoted string my_json_file.json is wrapped in parenthesis which doesn't even do anything in this case.
Assuming what you actually want is an array of file names to then open you'd want something like this:
$files = ['my_json_file.json'];
foreach($files as $file)
{
$contents = file_get_contents($file);
$json = json_decode($contents, true);
// foreach($json as $key => $value) { ...
}
I would highly recommend checking out this tutorial for the basics on handing JSON data in PHP.

Hardcode array for reuse in php file?

I don't know if this is even called "hardcoding", but I would like to build an array (for example from a mysqli_fetch_assoc query) and output it for reuse in a config.php file.
So this output from mysql would be:
[structure] => Array
(
[0] => Array
(
[structureid] => 23
[active] => 1
)
[1] => Array
(
[structureid] => 25
[active] => 1
)
And it would be stored like this in a config.php file:
$structure[0]['structureid'] = 23;
$structure[0]['active'] = 1;
$structure[1]['structureid'] = 25;
$structure[1]['active'] = 1;
Is there an easy and quick way to accomplish this?
As someone has pointed out, I could resolve this with using a json file - which I'm already doing - but I wanted to check if there would be another (quick) way of doing it as described above.
You can use var_export(), to create a readable (and in-code-reusable) array, that you can then put in a config file:
$reusableCode = var_export($yourArray, true);
Or to just output it:
var_export($yourArray);
You can put that in a config file with an return, like this:
return array(
'your' => 'values'
);
and then require it from your code:
$configData = require('yourConfigFileWithTheArray.php');
I Initially misread your question,
So you want to store mysql resource to a file?
You mentionned that you are using JSON is to solve this.
This is a good way to do it, the other way would be to serialize/deserialize the object than save them to a file. JSON solution is simple human readable.
Example:
$data = serialize($rows);
file_put_contents('data.txt', $data);
$data = file_get_contents('data.txt');
$rows = unserialize($data);
But you won't be able to read the output of the serialization.

PHP read file (array) as array

How can I read a json array and add/merge a new element to it?
The content of my file data.json looks like this array:
[["2015-11-24 18:54:28",177],["2015-11-24 19:54:28",178]]
new element array example:
Array ( [0] => Array ( [0] => 2015-11-24 20:54:28 [1] => 177 ) )
I used explode() and file() but it failed (delimiter for index 1..)..
has someone another idea or it is the right way to solve?
Firstly you need to import JSON content to your application as a string what can be done with file_get_contents().
After that you have to decode--or "translate"--JSON format to PHP primitives via json_decode(). The result will be the expected array to be handled.
Then you may append a new item to that array using [] suffix eg. $a[] = $b;
These three steps are exemplified below.
// get raw json content
$json = file_get_contents('data.json');
// translate raw json to php array
$array = json_decode($json);
// insert a new item to the array
$array[] = array('2015-11-24 20:54:28', 177);
In order to update the original file you have to encode PHP primitives to JSON via json_encode() and can write the result to desired file via file_put_contents().
// translate php array to raw json
$json = json_encode($array);
// update file
file_put_contents('data.json', $json);
<?php
$c = file_get_contents('data.json');
// <- add error handling here
$data = json_decode($c, true);
// <- add error handling here, see http://docs.php.net/function.libxml-get-errors
see http://docs.php.net/file_get_contents and http://docs.php.net/json_decode

PHP json_decode thrown an error for validate json string

I have following error
Notice: Trying to get property of non-object in action.php
while posted json has validated (by jsonLint.com validation).
Here is my json string:
[
{
"eTGid": "1",
"eTid": "34",
"evrakGelisTarihi": "12/12/2013",
"evrakKonu": "Sertifika denemesi",
"evrakKurumID": "1047",
"evrakCikisTarihi": "13/12/2013",
"evrakCikisSayisi": "313213213213",
"aciklamaBolumu": "açıklayıcı notlar",
"gelenEvrakTarihi": "30/12/2013",
"gelenEvrakSayisi": "3132321",
"gelenEvrakEtakipNo": "987654",
"bagliIlaclar": "[\"0\",\"[{\\\"ilacID\\\":\\\"744\\\",\\\"ilacPN\\\":\\\"asdasd2132\\\",\\\"ilacSKT\\\":\\\"12/12/2013\\\"}]\"]",
"bagliFirmalar": "[\"0\",\"[{\\\"firmaID\\\":\\\"1047\\\"}]\"]",
"": "[\"0\",\"[{\\\"bankaID\\\":\\\"5\\\",\\\"makbuzNO\\\":\\\"asdasda\\\",\\\"makbuzTARIHI\\\":\\\"12/12/2013\\\",\\\"ihracaatYapilacakUlkeID\\\":\\\"2\\\",\\\"ilacIhracADI\\\":\\\"ABFADER\\\",\\\"makbuzTUTAR\\\":\\\"202,06\\\",\\\"makbuzTipDetayDEGERİ\\\":\\\"10\\\"}]\",\"[{\\\"bankaID\\\":\\\"5\\\",\\\"makbuzNO\\\":\\\"ASDAWW\\\",\\\"makbuzTARIHI\\\":\\\"12/12/2013\\\",\\\"ihracaatYapilacakUlkeID\\\":\\\"191\\\",\\\"ilacIhracADI\\\":\\\"ABFADEX\\\",\\\"makbuzTUTAR\\\":\\\"202,06\\\",\\\"makbuzTipDetayDEGERİ\\\":\\\"9\\\"}]\"]",
"bagliMakbuzlar": "[\"0\",\"987654»12/12/2013»3213213\"]",
"kurumIcimi": "hayir"
}
]
and my php code is:
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj->{'eTGid'});
Where did I go wrong?
After suggestions:
My Json string has arrived to the serverside (php) as an array (between brackets).
Array has only one element (member) that it is our json string (object)
Handle the arrays first element and assign it to a php object and deal with it.
$gelenJsonVerisi = $_POST['yeniEvrak'];
$yeniEvrakObjArray = json_decode($gelenJsonVerisi,TRUE);
$yeniEvrakObj = $yeniEvrakObjArray[0];
exit($yeniEvrakObj['eTGid']); // one of sample value
Thank you
The JSON string shows an array, that contains a single object. access the data like so:
$yeniEvrakObj = json_decode($gelenJsonVerisi);
echo $yeniEvrakObj[0]->eTGid;
If you're sure there's but 1 object inside that array, you could try:
$yeniEvrakObj = json_decode(
substr($gelenJsonVerisi,1,-1)
);
Which chops off the leading and terminating brackets. This implies no leading of trailing whitespace, so trim the string first.
check codepad. As you can see, the json_decode call returns the data as an array containing an object:
Array
(
[0] => stdClass Object
(
[eTGid] => 1
[eTid] => 34
[evrakGelisTarihi] => 12/12/2013
[evrakKonu] => Sertifika denemesi
[evrakKurumID] => 1047
[evrakCikisTarihi] => 13/12/2013
[evrakCikisSayisi] => 313213213213
)
)
It's not json_decode throwing the error, it's when you try to access the resulting array. Yes, that's right, array. Your JSON value is this:
[ { ... } ]
^ array ^
So you need to access the result like:
$yeniEvrakObj[0]->eTGid
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj[0]->eTGid);
The problem is the way you're trying to access to the decoded object, as it is inside an array.
Your code should be:
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj[0]->eTGid);
Edit: Thanks for the comments on this answer that made me see I was mistaken

How to deserialize this string into a PHP array of key => value pairs?

I'm calling the script at: http://phat-reaction.com/googlefonts.php?format=php
And I need to convert the results into a PHP array format like the one I'm currently hard coding:
$googleFonts = array(
"" => "None",
"Abel"=>"Abel",
"Abril+Fatface"=>"Abril Fatface",
"Aclonica"=>"Aclonica",
etc...
);
The php returned is serialized:
a:320:{
i:0;
a:3:{
s:11:"font-family";
s:32:"font-family: 'Abel', sans-serif;";
s:9:"font-name";
s:4:"Abel";
s:8:"css-name";
s:4:"Abel";
}
i:1;
a:3:{
s:11:"font-family";
s:38:"font-family: 'Abril Fatface', cursive;";
s:9:"font-name";
s:13:"Abril Fatface";
s:8:"css-name";
s:13:"Abril+Fatface";
}
etc...
How can I translate that into my array?
You can do this by unserializing the data (using unserialize()) and then iterating through it:
$fonts = array();
$contents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$arr = unserialize($contents);
foreach($arr as $font)
{
$fonts[$font['css-name']] = $font['font-name'];
}
Depending on what you're using this for, it may be a good idea to cache the results so you're not fetching external data each time the script runs.
Use unserialize(): http://www.php.net/unserialize

Categories