Decode URL into an array rather than a string - php

I am currently working with PayPals API and want to transform one of its response from a name-value pair to an array.
So far I have used urldecode() to decode the response to the following:
RECEIVERBUSINESS=foo#bar.com&RECEIVEREMAIL=another#email.com&MOREINFO=lots more info`
What I would like is to have the following:
RECEIVERBUSINESS => 'foo#bar.com'
RECEIVEREMAIL => 'another#email.com'
MOREINFO => 'lots more info'
I'm just not quite sure how to get there!

parse_str is what you're looking for:
parse_str('RECEIVERBUSINESS=foo#bar.com&RECEIVEREMAIL=another#email.com&MOREINFO=lots more info', $arr);
/*
print_r($arr);
Array
(
[RECEIVERBUSINESS] => foo#bar.com
[RECEIVEREMAIL] => another#email.com
[MOREINFO] => lots more info
)
*/

Look into explode -
// poulate array from URL parameters
$returnedInfo = explode('&', $dataStringFromUrl);
http://us.php.net/explode

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

PHP: Trying to insert Twilio response JSON into MySQL TEXT field, but string is being truncated, possibly before the insert

Wordpress 5.3.2 and PHP 7.2 on localhost.
I'm sending a Twilio sms, and capturing the response from Twilio, which is JSON.
I want to store the response, because in it are all kinds of goodies, like the send date-time stamp.
When I make a test file, and print_r the response, it is a rather large JSON object. Not sure I should even post it here, at 11,568 characters. Here's a partial output (Acct values have been slightly altered):
Twilio\Rest\Api\V2010\Account\MessageInstance Object
(
[_media:protected] =>
[_feedback:protected] =>
[version:protected] => Twilio\Rest\Api\V2010 Object
(
[_accounts:protected] =>
[_account:protected] => Twilio\Rest\Api\V2010\AccountContext Object
(
[_addresses:protected] =>
[_applications:protected] =>
[_authorizedConnectApps:protected] =>
[_availablePhoneNumbers:protected] =>
[_calls:protected] =>
[_conferences:protected] =>
[_connectApps:protected] =>
[_incomingPhoneNumbers:protected] =>
[_keys:protected] =>
[_messages:protected] => Twilio\Rest\Api\V2010\Account\MessageList Object
(
[version:protected] => Twilio\Rest\Api\V2010 Object
*RECURSION*
[solution:protected] => Array
(
[accountSid] => AC3365f6c6dddaac48edfb902a3e1b8688d
)
[uri:protected] => /Accounts/AC3365f6c6dddaac48edfb902a3e1b8688d/Messages.json
)
[_newKeys:protected] =>
(etc., etc...)
My test code looks like this:
$data['numbers'] = array( "9541234567");// phone numbers of sms recipients. Just one for now.
$count = array();
for($i=0;$i<count($data['numbers']);$i++){
$args = array(
'number_to' => $data['numbers'][$i],
'message' => "This is a test.\n",
);
$sent = twl_send_sms( $args );
echo "<pre>";
print_r($sent);//This line outputs that beautiful, robust JSON string I am after.
echo "</pre>";
}
...so far, so good. The Twilio sms sends, and Twilio gives me a nice large response in JSON format.
Now, I transfer my code to the larger, production context, and I want to capture that 11,568 character JSON object, and store it in a table (by means of update). I think it should be a TEXT type, which is probably correct.
Here is my slightly revised code for production:
$data['twilio_response'] = twl_send_sms( $args ); //This sends the sms, captures a Twilio response into an array element.
$table = $wpdb->prefix . "npf_notifications";
$data['notification-update'] = $wpdb->update(
$table,
array('twilio_response' => $data['twilio_response']),
array('id' => $data['notifications-insert']['id']),
array('%s'),
array('%s')
);
$data['notification-update-query'] = $wpdb->last_query; // this records the query in an array element, so I can examine it.
Unfortunately for me, I don't get anything near as complete as the raw JSON from my test script. Instead, my Twilio response JSON looks like this:
notification-update-query = UPDATE `xsdslp_npf_notifications` SET `twilio_response` = '[Twilio.Api.V2010.MessageInstance accountSid=AC3365f6c6dceec35edfb902a3e1b8688d sid=SMfeb33b00895e455091445e4901547e70]' WHERE `id` = '5e092437a6037_1577657399'
...and the value of the array element to which I assign my Twilio response data looks like (after printing it out using javascript):
$data['twilio_response'] = [Twilio.Api.V2010.MessageInstance accountSid=AC3365f6c6ddaac48edfb902a3e1b8688d sid=SMfeddaac485e455091445e4901547e70]
It looks like the MySQL update (or insert) isn't the problem, but the JSON response string is being shortened in my array element variable. Can someone out there tell me what I'm doing wrong?
looks like you need to use json_encode() on $data['twilio_response'] first, because the returned object from twl_send_sms is not a JSON string, but a PHP object. Alternatively you can use serialize()

How to get a string from requested array PHP

I have a file swifts.php with code (I have written this after a lot of research)
<?php
$swift= array(
'PBANUA2XXXX' => 'PRIVATBANK',
'Swift2' => 'word2',
'Swift3' => 'word3',
'Swift4' => 'word4',
'Swift5' => 'word5',
'etc' => 'word6',
'etc..' => 'word7',
);
echo http_build_query($swift) . "\n";
echo http_build_query($swift, '', '&');
?>
My question is how to receive a string for example when I request the Swift3 with https://example.com/swifts.php?swift=Swift3
I want to receive in a page just the string word3 but it shows me all the arrays like: PBANUA2XXXX=PRIVATBANK&Swift2=word2&Swift3=word3& etc etc....
How I can get what I request?
You have to get query string by using $_GET.
Then use your array to get value
echo $swift[$_GET['swift']]; // as $_GET['swift'] = Swift3
so $swift[$_GET['swift']] = 'word3';

Problem inserting string into array

i'm trying to insert an implode generated string to an array that then later be used for json implementation
the implode generated string is look like this
'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]
i would like to used it in this code
$this->_JsonArr[]=array($Generated string);
to achieve something like this
$this->_JsonArr[]=array('id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]);
instead i got something like this
$this->_JsonArr[]=array(" 'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]");
seem like generated string is treated as one element as key and value pair.
obviously i can get expected output from mysql because of this, can anybody help me with this
Why do you need to implode anything? Just pass the array:
$this->_JsonArr[] = your-non-imploded-array-here;
I think a full solution to what you want to do is something like this (i.e., the third code box in your question):
$row = array(
'id' => $this->_SqlResult[0],
'UserId' => $this->_SqlResult[1],
'Msg' => $this->_SqlResult[2],
'MsgStamp' => $this->_SqlResult[3]
);
$this->_JsonArr[] = $row;
$this->_JsonArr[]=array($Generated
string);
Looks like you want use arrays keys and values, but as I see you put into array plain string with expectation that array parse your plain string in format: keys => values.
You can try create array like below:
$this->_JsonArr[ $Generated_key ] = array( $Generated_value );
(Please correct me if I wrong understand your question).

Parsing HTTP data into PHP variables

I have a reasonably large number of variables encoded in the form:
foo=bar&spam[eggs]=delicious&...
These are all in a single string (eg, $data = "foo=bar&spam[eggs]=delicious&..."). The variables are arbitrarily deeply nested -- easily four or five levels deep ("spam[eggs][bloody][vikings]=loud").
Is there an easy, reliable way to get a multi-dimensional PHP array from this? I assume PHP has a parser to do this, though I don't know if it's exposed for my use. Ideally, I could do something like:
// given $data == "foo=bar&spam[eggs]=delicious"
$arr = some_magical_function( $data );
/* arr = Array
(
[foo] => bar
[spam] => Array
(
[eggs] => delicious
)
)
*/
If your string is in URI params format, parse_str is the magic function you are looking for.
You might want to take a look at parse_str ; here's an example :
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
And, with your input :
$str = 'oo=bar&spam[eggs]=delicious&spam[eggs][bloody][vikings]=loud';
$output = array();
parse_str($str, $output);
var_dump($output);
You'll get this :
array
'oo' => string 'bar' (length=3)
'spam' =>
array
'eggs' =>
array
'bloody' =>
array
'vikings' => string 'loud' (length=4)
Which should be what you want ;-)
(notice the multi-level array ; and the fact that ths first spam[eggs] has been overriden by the second one, btw)
If your data comes from the request uri, use $_GET

Categories