How can I decode a JSON string in PHP? - php

I am trying to read a string into an array in PHP, but it doesn't work for me.
The string I would like to read:
$output = {"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}
The code I am using:
$arr = explode(',', $output);
foreach($arr as $v) {
$valarr = explode(':', $v);
preg_match_all('/"(.*?)"/', $valarr[0], $matches);
$narr[$matches[1][0]][$matches[1][1]] = $valarr[1];
}
Specifically, I would like to access the value for 'message' (i.e., 'Approved').
I tried this, but it still fails:
echo 'MESSAGE ' . $arr['message'];

Here is working code,
$arr = '{"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}';
$arr = json_decode($arr, true);
echo $arr['message'];
print_r($arr);
Here is working link

Thats not string, its json..
$array = json_decode($output,true);

Related

Broke string into vars with variable position

I need to broke a string into some vars but its order is not fixed as the exemple:
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
so I need to broke the strings into:
$name
$phone
$city
if the position would be fixed i could use explode and call for the array key that i need like
$brokenString = explode("'",$string);
$name = $brokenString[1];
$phone = $brokenString[3];
$city = $brokenString[5];
however how could I do it with variable position??
One way to do it with sort to make the position same always for all string variables.
<?php
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
$array = explode(';',$string3);
sort($array);
$array = array_filter($array); # remove the empty element
foreach($array as $value){
$split = explode('=',$value);
$result[$split[0]] = $split[1];
}
extract($result); # extract result as php variables
echo "\$city = $city; \$name = $name; \$phone = $phone";
?>
EDIT: As using extract() is generally not a good idea.You can use simple foreach() instead of extract(),
foreach($result as $k => $v) {
$$k = $v;
}
WORKING DEMO: https://3v4l.org/RB8pT
There might be a simpler method, but what I've done is created an array $stringVariables which holds the exploded strings.
This array is then looped through and strpos is used in each element in the exploded string array to see if it contains 'city', 'phone', or 'name'. Depending on which one, it's added to an array which holds either all the names, cities or phone numbers.
$stringVariables = array();
$phones = array();
$names = array();
$cities = array();
$stringVariables[] = explode(";",$string);
$stringVariables[] = explode(";",$string2);
$stringVariables[] = explode(";",$string3);
foreach($stringVariables as $stringVariable) {
foreach($stringVariable as $partOfString) {
if(strpos($partOfString, "name=") !== false) {
$names[] = $partOfString;
}else if(strpos($partOfString, "city=") !== false) {
$cities[] = $partOfString;
}else if(strpos($partOfString, "phone=") !== false) {
$phones[] = $partOfString;
}
}
}
An alternative way is to convert it into something that can be parsed as a URL string.
First part is to change the values and , from 'John', to John& using a regex ('([^']+)'; which looks for a ' up to a ' followed by a ;), then parse the result (using parse_str())...
$string = "name='John';phone='555-5555';city='oakland';";
$string = preg_replace("/'([^']+)';/","$1&", $string);
echo $string.PHP_EOL;
parse_str( $string, $values );
print_r($values);
gives the output of
name=John&phone=555-5555&city=oakland&
Array
(
[name] => John
[phone] => 555-5555
[city] => oakland
)
or just using regex's...
preg_match_all("/(\w*)?='([^']+)';/", $string, $matches);
print_r(array_combine($matches[1], $matches[2]));

Send array value in a URL parameter

I'm having issues building a proper URL parameter sent to a service. I need to send dynamic query results in one parameter. Here's what I have reached so far:
<a href="https://serviceurl/?language=EN&variable1=<?php
$mobiles = array();
while($row_query = mysql_fetch_assoc($query))
{
$data = $row_query['rowwithvalues'];
$myArray = implode(',', $data);
foreach($myArray as $my_Array){
echo $my_Array;
}
}
?>&variable2=Hello">Test</a>
The above returns a blank value for variable1 in the url.
Thanks in advance!
When you calling $myArray = implode(',', $data); it makes $myArray string from implode doc:
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
So you cannot loop on it - I guess you wanted to use explode. Try this:
<a href="https://serviceurl/?language=EN&variable1=
<?php
while($row_query = mysql_fetch_assoc($query)) {
$data = $row_query['rowwithvalues'];
$myArray = explode(',', $data);
foreach($myArray as $my_Array){
echo $my_Array;
}
}
?>&variable2=Hello">Test</a>

How to convert specific strings to int from dynamic json's url?

I would like to remove "" from a few strings from json which updates every few minutes (http://zergpool.com/api/status).
for example:
{"bitcore":{"name":"bitcore","port":3556,"coins":1,"fees":0,"hashrate":0,"workers":0,"estimate_current":"0.00001745","estimate_last24h":"0.00001756","actual_last24h":"0.00000","hashrate_last24h":105820474.1458},
Fields:
"estimate_current":"0.00001745" -> "estimate_current":0.00001745
"estimate_last24h":"0.00001756" -> "estimate_last24h":0.00001756
"actual_last24h":"0.00000" -> "actual_last24h":0.00000
Since the numbers change all the time, is it possible to write a PHP to convert them in real time? This is what I did.
<?php
$url = 'http://zergpool.com/api/status';
$data = file_get_contents($url);
$manage = json_decode($data,true);
//$aha = (int)preg_replace("/[^\d]+/","",$manage); // tried removing them like this... doesn't work.
echo json_encode($manage)
doesn't work :(
You can use this to remove quotes from numeric values in JSON.
$encoded = json_encode($data, JSON_NUMERIC_CHECK);
Supported in the versions >= PHP 5.3
echo str_replace( '"', '' ,$data);
will remove all the double quotes.
I don't understand why you are trying to remove the double quotes from the $manage line. You can just access the elements of the json that are returned in $manage and convert to float.
$firstString = $manage['bitcore']['estimate_current'];
$firstFloat = (float)$firstString;
var_dump($firstFloat);
or
echo 'floatval=' . floatval($firstString);
Try this:
$json = file_get_contents("https://www.ahashpool.com/api/status/");
$ar = json_decode($json, TRUE);
$filter = [];
foreach ($ar as $k => $sub_ar) {
foreach ($sub_ar as $sub_k => $sub_v) {
if(preg_match('/^[0-9]*\.[0-9]+$/', $sub_v)){
$filter[$k][$sub_k] = (float) $sub_v;
} else {
$filter[$k][$sub_k] = $sub_v;
}
}
}
echo "<pre>";
var_dump($filter);
die();

Regex not working properly in PHP

I have this data:
{"names":["George","Eric","Alice"]}
And I want to use preg_match_all to filter out the words in between quotation like this:
$s = $data;
if (preg_match_all('/"([^:]*)"/', $s, $matches)) {
echo join("\n", $matches[1]);
}
But this is outputting names George","Eric","Alice I tried many things but I cant figure it out.
* matches greedy (as much as possible). Use non-greey version: *?
if (preg_match_all('/"([^:]*?)"/', $s, $matches)) {
echo join("\n", $matches[1]);
}
output:
names
George
Eric
Alice
UPDATE
json_decode is more appropriate for this kind of work. Try following:
foreach (json_decode($s, true) as $key => $value) {
echo $key . "\n";
echo join("\n", $value);
}
This is actually JSON string use json_decode to parse it rather than using regex on this:
print_r(json_decode('{"names":["George","Eric","Alice"]}', true));
OUTPUT:
Array
(
[names] => Array
(
[0] => George
[1] => Eric
[2] => Alice
)
)
try this
$strContent = '{"names":["George","Eric","Alice"]}';
$strRegex = '%\"(.+?)\"%s';
if (preg_match_all($strRegex, $strContent, $arrMatches))
{
var_dump($arrMatches[1]);
}
Since your data is json formatted you should really treat is as json and not process it with regex which is to be used for strings. Try this:
$json = '{"names":["George","Eric","Alice"]}';
$data = json_decode($json, true);
foreach($data['names'] as $item) echo "$item\n";
Or without the hard coded "names":
$json = '{"names":["George","Eric","Alice"]}';
$data = json_decode($json, true);
foreach($data as $arr) foreach($arr as $item) echo "$item\n";

PHP read and write JSON from file

I have the following JSON in a file list.txt:
{
"bgates":{"first":"Bill","last":"Gates"},
"sjobs":{"first":"Steve","last":"Jobs"}
}
How do I add "bross":{"first":"Bob","last":"Ross"} to my file using PHP?
Here's what I have so far:
<?php
$user = "bross";
$first = "Bob";
$last = "Ross";
$file = "list.txt";
$json = json_decode(file_get_contents($file));
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
?>
Which gives me a Fatal error: Cannot use object of type stdClass as array on this line:
$json[$user] = array("first" => $first, "last" => $last);
I'm using PHP5.2. Any thoughts? Thanks!
The clue is in the error message - if you look at the documentation for json_decode note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.
So change your call to
$json = json_decode(file_get_contents($file), true);
And it'll return an associative array and your code should work fine.
The sample for reading and writing JSON in PHP:
$json = json_decode(file_get_contents($file),TRUE);
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
Or just use $json as an object:
$json->$user = array("first" => $first, "last" => $last);
This is how it is returned without the second parameter (as an instance of stdClass).
You need to make the decode function return an array by passing in the true parameter.
json_decode(file_get_contents($file),true);
Try using second parameter for json_decode function:
$json = json_decode(file_get_contents($file), true);
This should work for you to get the contents of list.txt file
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str=utf8_encode($str);
$str=json_decode($str,true);
print_r($str);
If you want to display the JSON data in well defined formate you can modify the code as:
file_put_contents($file, json_encode($json,TRUE));
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str1=utf8_encode($str);
$str1=json_decode($str1,true);
foreach($str1 as $key=>$value)
{
echo "key is: $key.\n";
echo "values are: \t";
foreach ($value as $k) {
echo " $k. \t";
# code...
}
echo "<br></br>";
echo "\n";
}
When you want to create json format it had to be in this format for it to read:
[
{
"":"",
"":[
{
"":"",
"":""
}
]
}
]

Categories