Best way to parse this response into an associative array? - php

Below is the response I'm getting after posting to an API.... I don't think parse_url is going to cut it. Are there any built in PHP functions or better ways to turn this into an array? This is the output of var_dump
sting(163) "response=3&responsetext=Duplicate transaction REFID:115545335&authcode=&transactionid=&avsresponse=&cvvresponse=&orderid=&type=auth&response_code=300&processor_id="

Use parse_str() with the optional $arr parameter.
Parses str as if it were the query string passed via a URL

You are looking for parse_str.
It turns a query string into an associative array.

I propose :
$elements = explode('&', $input);
$data = array();
foreach($elements as $e) {
$d = explode('=', $e);
$data[$d[0]] = isset($d[1]) ? $d[1] : '';
}
But maybe there is a better way.

Related

How do I get an Expression out of a string in PHP?

Please, how do I extract an expression from a string?
For example, I have this string below:
RECEIPT_NO=5001809252729&PAYMENT_CODE=500858991537884262034&MERCHANT_CODE=0350000AFT&TRANS_AMOUNT=42990.0&TRANS_DATE=2018/09/25 14:04:28&TRANS_DESCR=Victor-300%20Level%20-001-
What I want to do is compare the value inputted by a user with the value in bold
How do I go about it using PHP?
I had tried using str_split('/[&]/', $string);, but I wasnt getting what I wanted. Please help.
Thanks.
You have a string in standard HTTP "query string" format (percent-encoded and &-separated key=value pairs). The easiest way to handle it is using PHP's built-in parse_str() function:
$items = [];
parse_str($string, $items);
echo $items["PAYMENT_CODE"];
If this function did not exist, you could reimplement it;
$items = [];
foreach (explode("&", $string) as $item) {
list($key, $val) = explode("=", $item, 2);
$items[urldecode($key)] = urldecode($val);
}
You must use explode() in PHP;
In your case like this :
$str = 'RECEIPT_NO=5001809252729&PAYMENT_CODE=500858991537884262034&MERCHANT_CODE=0350000AFT&TRANS_AMOUNT=42990.0&TRANS_DATE=2018/09/25 14:04:28&TRANS_DESCR=Victor-300%20Level%20-001-';
$arrayOfVars = explode('&',$str);
look at explode() documentation in PHP.net

Extracting data from Json in Php

I have this Json Object Below, I want to extract this data and output it in PHP
{"seat_booked":"A5","0":"A5","1":"A3"}
then get them into this format
$seat_booked = "'A5', 'A5', 'A3'";
How can I do this?
I hope you are looking for this, its very simple example by using json_decode():
$string = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = json_decode($string,true);
$resuiredString = '"'."'".implode("','", $decoded)."'".'"';
echo $resuiredString;
Result:
"'A5','A5','A3'"
Side Note:
I suggest you to learn about variable concatenation.
PHP Concatenation
Another solution:
$json = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = array_map(
function($val) {
return "'". $val."'";
},
array_values(json_decode($json, true))
);
To get an object from a json in php you can use json_decode has explained here.
But you have another problem, your json is wrong!
If you want to represent a single dimensional array you should at least do this
["A5","A5","A3"]
Finally, using json_decode:
$obj = json_decode('["A5","A5","A3"]');
var_dump($obj);
Also, you could do something like:
{"0":"A5","1":"A5","2":"A3"}
$obj = json_decode('{"0":"A5","1":"A3", "2": "A5"}', true);
var_dump($obj);
Edit:
It's not very clear from your question if you are trying to get back an object from a json or if you just want to get a string from it.
If what you need is an string then you don't even need json, you could do this by string manipulation and/or using regex.
But just for completeness, if a quoted comma separated string is what you need you can do this:
$array = json_decode('["A5","A5","A3"]');
$str = implode("','",$array);
$str = "'" . $str . "'";
var_dump($str);

Extract JSON Array from data

I am requesting data from another website and expecting a clean json array in return.
However I am getting this instead:
<pre></pre>{"Status":"Success","Result":1}
which won't parse with json_decode();.
How do I extract the JSON array out of this data so I can parse it?
Note: I am not in control of the code I am requesting the data from.
try this
$output_array = array();
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
preg_match("/{.*}/", $badstr, $output_array);
in $output_array[0] you have your json string.
Assuming that <pre></pre> is constant, then just a simple substring operation:
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
$goodstr = substr($badstr, 11);
But you really should yell at the server admins for sending out bad json in the first place. There's no excuse for this kind of thing. It's probably some debug code they forgot to take out.
If you want it to work both now, and once the issue will be fixed, you can do this:
$result = '<pre></pre>{"Status":"Success","Result":1}';
if (strpos($result ,'<pre>') !== false)
{
$array = json_decode(substr($result , 11));
}
else
{
$array = json_decode($result);
}
Only remove <pre></pre>, only if it's the first thing:
$response = preg_replace('#^<pre></pre>#', '', $response);
How about simply string replace?
Like so:
$json_string = '<pre></pre>{"Status":"Success","Result":1}';
$json = str_replace("<pre></pre>", "", $json_string);
echo $json;
Output:
{"Status":"Success","Result":1}
If you don't expect any html tags in your output, you can also use strip_tags():
$not_json = '<pre></pre>{"Status":"Success","Result":1}';
$json_string = strip_tags($json);
$result = json_decode($json_string);

get the results of curl in variables

i got a piece of code that so far returns me data like this when i use print $result;
ssl_card_number=41**********1111
ssl_exp_date=0213
ssl_amount=132.86
ssl_salestax=0.00
ssl_invoice_number=5351353519500
ssl_result=0
ssl_result_message=APPROVED
ssl_txn_id=00000000-0000-0000-0000-00000000000
ssl_approval_code=123456
ssl_cvv2_response=P
ssl_avs_response=X
ssl_account_balance=0.00
ssl_txn_time=11/21/2012 12:38:20 PM
thats from view page source.
and the page itself shows it as :
ssl_card_number=41**********1111 ssl_exp_date=0213 ssl_amount=132.86 ssl_salestax=0.00 ssl_invoice_number=8601353519473 ssl_result=0 ssl_result_message=APPROVED ssl_txn_id=00000000-0000-0000-0000-00000000000 ssl_approval_code=123456 ssl_cvv2_response=P ssl_avs_response=X ssl_account_balance=0.00 ssl_txn_time=11/21/2012 12:37:54 PM
i need to be able to handle each of the "keys" in a better way and dont know how to explode them maybe ?
One possible approach:
parse_str(preg_replace('#\s+(?=\w+=)#', '&', $result), $array);
var_dump($array);
Explanation: preg_replace will turn all the whitespace before the param names into '&' symbol - making this string similar to the regular GET request url. Then parse_str (the function created specifically for parsing such urls) will, well, parse this string (sent as the first param), making an associative array of it.
In fact, you don't even have to use preg_replace here, if each param=value string begins from a new line; str_replace("\n", '&') should do the trick.
An alternative approach:
$pairs = preg_split('#\s+(?=\w+=)#', $x);
foreach ($pairs as $pair) {
list ($key, $value) = explode('=', $pair, 2);
$array[$key] = $value;
}
Here you first create an array of 'key-value pair' strings, then split each element by =: the first part would be the key, the second - the value.
You can use the regular expression reported by #raina77ow or you could use explodes (riskier):
<?php
$tmps = explode("\n",$result); //this gives you each line separate
foreach($tmps as $tmp){
list($key,$value) = explode('=',$tmp,2);
echo $key.' has value '.$value."\n";
//you can even create vars with the "key" if you are sure that they key is a "clean" string:
$$key=$value;
//or put everything into an array - similar to the regexp
$result_array[$key] = $value;
}
?>

getting value using explode

I am trying to parse following string...
IN.Tags.Share({"count":180,"url":"http://domain.org"}
is my following approach correct to get the value of count?
$str = 'IN.Tags.Share({"count":180,"url":"http://domain.org"}';
$data = explode(':', $str);
$val = explode(',', $data[1]);
return $val[0];
Or is there any better way to handling this type of strings? I think it could be done using regex as well.
thanks.
If course I'm not sure if your format will be constant, but part of your string looks like JSON. If always like this, you could do:
$str = str_replace('IN.Tags.Share(', '', $str);
$values = json_decode($str);
echo $values->count;
I would suggest pulling out the JSON by applying this regex to the string: IN\.Tags\.Share\((.*)\. Pull out the first group, and use json_decode: http://php.net/manual/en/function.json-decode.php
That way, you can directly access the data. It will support complex data structures as well.

Categories