I am working on Paypal Payflow for payment and right now I am having trouble extracting the Paypal response.
Paypal responses are sent in a format as given below
RESULT=0&RESPMSG=Approved&SECURETOKEN[25]=Fj+1AFUWft0+I0CUFOKh5WA== &SECURETOKENID=9a9ea8208de1413abc3d60c86cb1f4c5
The value inside the square braces [] is the length of the actual value. For example, SECURETOKEN is a parameter and it's value is 'Fj+1AFUWft0+I0CUFOKh5WA=='. is 25 characters long.
How can I extract each parameter and it's corresponding value from the result in PHP. I am not so good with regex and I was unable to find any solution online.
Splitting with & and = does not work in this case.
The string looks an url, so the simple approch is use [parse_str()][1] it will transform the given string into an array 'well formated'.
Important the return of function will be store in the second argument ($keys in this example).
Ideone - example
$str = 'RESULT=0&RESPMSG=Approved&SECURETOKEN[25]=Fj+1AFUWft0+I0CUFOKh5WA== &SECURETOKENID=9a9ea8208de1413abc3d60c86cb1f4c5';
parse_str($str, $keys);
print_r($keys);
Output:
Array
(
[RESULT] => 0
[RESPMSG] => Approved
[SECURETOKEN] => Array
(
[25] => Fj 1AFUWft0 I0CUFOKh5WA==
)
[SECURETOKENID] => 9a9ea8208de1413abc3d60c86cb1f4c5
)
Using this answer to parse the response into an array is the correct start. This is how to access those values from the array:
$str = 'RESULT=0&RESPMSG=Approved&SECURETOKEN[25]=Fj+1AFUWft0+I0CUFOKh5WA== &SECURETOKENID=9a9ea8208de1413abc3d60c86cb1f4c5';
parse_str( $str, $values );
Now, to get the values you want:
$tokens = $values['SECURETOKEN'];
// results in an array: ['25' => 'Fj+1AFUWft0+I0CUFOKh5WA=='];
$token = reset( $tokens ); // results in 'Fj+1AFUWft0+I0CUFOKh5WA=='
$length = key( $tokens ); // results in '25'
Related
This question already has answers here:
How create an array from the output of an array printed with print_r?
(11 answers)
Closed 1 year ago.
Array ( [status] => 1 [message] => Logged In Successfully. )
I Want to access status from this array like string.
I fetch this Response from API.
It's look not good.not like array or not like json.
I am not able to access key,so any one can help me, now.
You could achieve this using preg_match perhaps? See it working over at 3v4l.org but it is not a very dynamic solution and I'm assuming the status will always be a single integer.
preg_match('/(\Sstatus\S => \d)/',
'Array ( [status] => 1 [message] => Logged In Successfully. )',
$matches
);
if(!empty($matches))
{
$status = (int) $matches[0][strlen($matches[0]) -1]; // 1
}
To improve #Jaquarh's answer, you could write this function that helps you extract the values using any desired string, key and expected type.
I have added a few features to the function like not minding how many spaces come between the => separator in the string, any value-type matching, so that it can retrieve both numeric and string values after the => separator and trimming of the final string value. Finally, you have the option of casting the final value to an integer if you want - just supply an argument to the $expected_val_type argument when you call the function.
$my_str is your API response string, and $key_str is the key whose value you want to extract from the string.
function key_extractor($my_str, $key_str, $expected_val_type=null) {
// Find match of supplied $key_str regardless of number of spaces
// between key and value.
preg_match("/(\[" . $key_str . "\]\s*=>\s*[\w\s]+)/", $my_str, $matches);
if (!empty($matches)) {
// Retrieve the value that comes after `=>` in the matched
// string and trim it.
$value = trim(substr($matches[0], strpos($matches[0], "=>") + 2));
// Cast to the desired type if supplied.
if ($expected_val_type === 'int') {
return ((int) $value);
}
return $value;
}
// Nothing was found so return null.
return NULL;
}
You could then use it like this:
key_extractor($res, 'status', 'int');
$res is your API response string.
I am using an API that returns a CSV string as the following:
Date,Open,High,Low,Close,Volume,Adj Close 2014-06-13,3.10,3.30,3.10,3.30,6638300,3.30
I was wondering if there is an easy way to convert this CSV string to an associative array? I am familiar with working with a CSV file, but not sure what to do with a CSV file string response. I am trying to avoid writing the response to a file, just so I can read it back.
Note, writing this response to a CSV file would result in two rows and seven columns.
If the line terminator is \r\n, then first you need to explode them thru that. Then you can proces from there. Consider this example:
$data = explode("\r\n", $csv_string);
// get the headers first
$headers = array_map('trim', explode(',', array_shift($data)));
$new_data = array();
// get the values and use array combine to use the headers as keys for associative array
foreach($data as $values) {
$pieces = explode(',', $values);
// i just assigned it in an array, since we dont know how many lines of data you will receive
$new_data[] = array_combine($headers, $pieces);
}
$new_data should yield something like this:
Array
(
[0] => Array
(
[Date] => 2014-06-13
[Open] => 3.10
[High] => 3.30
[Low] => 3.10
[Close] => 3.30
[Volume] => 6638300
[Adj Close] => 3.30
)
)
Or just the usual way of handling csv strings. Use str_getcsv().
$data = str_getcsv($csv_string, "\r\n");
$headers = explode(',', array_shift($data));
$data = array_combine($headers, explode(',',reset($data)));
As others have mentioned, str_getcsv() is your friend and is an easy method to convert a CSV string into an array. This function will return an array of results. If you'd like to make it an associative array, use array_combine().
Honestly, though -- str_getcsv() may be overkill. Consider this method using explode():
// so given this string returned by the API
$api_s = "Date,Open,High,Low,Close,Volume,Adj Close\r\n2014-06-13,3.10,3.30,3.10,3.30,6638300,3.30";
// split on carriage return & line feed into two strings
$api_r = explode("\r\n", $api_s);
// split keys and values by comma
$keys = explode(',', $api_r[0]);
$vals = explode(',', $api_r[1]);
// construct associative array
$my_assoc_r = array_combine($keys, $vals);
Suppose I've got the following string:
) [6] => Array ( [2014-05-05 00:0] => My actual content
If I want to only be left with My actual content at the end, what is the best way to split the entire string?
Note: the words My actual content are and can change. I'm hoping to cut the string based on the second => string as this will be present at all times.
It seems you're just looking to find the first value of an array with keys you do not know. This is super simple:
Consider the following array:
$array = array(
'2014-05-22 13:36:00' => 'foo',
'raboof' => 'eh',
'qwerty' => 'value',
'8838277277272' => 'test'
);
Method #1:
Will reset the array pointer to the first element and return it.
Using reset:
var_dump( reset($array) ); //string(3) "foo"
DEMO
Method #2:
Will reset the entire array to use keys of 0, 1, 2, 3...etc. Useful if you need to get more than one value.
Using array_values:
$array = array_values($array);
var_dump( $array[0] ); //string(3) "foo"
DEMO
Method #2.5:
Will reset the entire array to use keys of 0, 1, 2, 3...etc and select the first one into the $content variable. Useful if you need to get more than one value into variables straight away.
Using list and array_values:
list( $content ) = array_values($array);
var_dump( $content ); //string(3) "foo"
DEMO
Method #3:
Arrays are iteratable, so you could iterate through it but break out immediately after the first value.
Using a foreach loop but break immediatly:
foreach ($array as $value) {
$content = $value;
break;
}
var_dump($content); //string(3) "foo"
DEMO
To Answer your question, on extracting from a string based on last 'needle'...
Okay, this is quite an arbitrary question, since it seems like you're showing us the results from a print_r(), and you could reference the array key to get the result.
However, you mentioned "... at the end", so I'm assuming My actual content is actually right at the end of your "String".
In which case there's a very simple solution. You could use: strrchr from the PHP manual - http://www.php.net/manual/en/function.strrchr.php.
So you're looking at this: strrchr($string, '=>');
Hope this answers your question. Advise otherwise if not please.
you have to use foreach loop in a foreach to get the multi dimentional array values.
foreach($value as $key){
foreach($key as $val){
echo $val;
}
}
Here's an array:
array('csv'=>
array('path'=>'/file.csv',
'lines'=>array('line1',
'line2',
'line3'
)
)
)
As you can see, the array goes three levels deep.
Here are two strings:
1. 'csv/path'
2. 'csv/lines/0
Using / as the delimiter, string 1 will get '/file.csv' and string 2 will get 'line1'. I've been thinking about using a recursive function, but I just don't know yet how to go about it.
The idea is I won't know which array key I'm accessing. I'm working on creating a generic function that will take a string as input and return the respective value in the array.
Demo
Just iterate through each key from the string given, setting the new array to pull from as the found element in the given array. You should add error handling.
<?php
$array = array('csv'=>
array('path'=>'/file.csv',
'lines'=>array('line1',
'line2',
'line3'
)
)
);
echo extractData($array, 'csv/path'); // echoes /file.csv
echo extractData($array, 'csv/lines/0'); // echoes line1
function extractData($array, $string){
$keys = explode('/', $string);
$data = $array;
foreach ($keys as $key){
$data = $data[$key];
}
return $data;
}
I am new PHP question and I am trying to create an array from the following string of data I have. I haven't been able to get anything to work yet. Does anyone have any suggestions?
my string:
Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35
I want to dynamically create an array called "My_Data" and have id display something like my following, keeping in mind that my array could return more or less data at different times.
My_Data
(
[Acct_Status] => active
[signup_date] => 2010-12-27
[acct_type] => GOLD
[profile_range] => 31-35
)
First time working with PHP, would anyone have any suggestions on what I need to do or have a simple solution? I have tried using an explode, doing a for each loop, but either I am way off on the way that I need to do it or I am missing something. I am getting something more along the lines of the below result.
Array ( [0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35} )
You would need to explode() the string on , and then in a foreach loop, explode() again on the = and assign each to the output array.
$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35";
// Array to hold the final product
$output = array();
// Split the key/value pairs on the commas
$outer = explode(",", $string);
// Loop over them
foreach ($outer as $inner) {
// And split each of the key/value on the =
// I'm partial to doing multi-assignment with list() in situations like this
// but you could also assign this to an array and access as $arr[0], $arr[1]
// for the key/value respectively.
list($key, $value) = explode("=", $inner);
// Then assign it to the $output by $key
$output[$key] = $value;
}
var_dump($output);
array(4) {
["Acct_Status"]=>
string(6) "active"
["signup_date"]=>
string(10) "2010-12-27"
["acct_type"]=>
string(4) "GOLD"
["profile_range"]=>
string(5) "31-35"
}
The lazy option would be using parse_str after converting , into & using strtr:
$str = strtr($str, ",", "&");
parse_str($str, $array);
I would totally use a regex here however, to assert the structure a bit more:
preg_match_all("/(\w+)=([\w-]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);
Which would skip any attributes that aren't made up of letters, numbers or hypens. (The question being if that's a viable constraint for your input of course.)
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35';
parse_str(str_replace(',', '&', $myString), $myArray);
var_dump($myArray);