How to Send 2D array through php cURL - php

I'm working with a a distributed system where a php app sends a post request to a python app.
My code is pretty straight forward:
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
I have a 2d php array that looks like:
array(3) { [0]=> array(2) { ["a"]=> 'aaa' ["token"]=> string(55) "146bf00b2cb8709" } [1]=> array(2) { ["a"]=> string(52) "bbb" ["token"]=> string(55) "146bf00b2cb96e74302" } [2]=> array(2) { ["a"]=> string(52) "ccc" ["token"]=> string(55) "146bf00b2cb96e6c422417" } }
I want to transmit this via php curl, but I'm not sure how to do this in a way that is decodable on the other end in python.

php
// 2d array
$arr = array(array(1,2,3),array(4,5,6),array(7,8,9));
// 2d array into json
$json = json_encode($arr) // [[1,2,3],[4,5,6],[7,8,9]]
send($json)
python
import json
r = request.body # receives request from php
json = json.loads(r)
print json[0] # [1,2,3]

curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
Will encode your request as an HTTP query and transform your data into a multipart/form-data.
The python application must be an HTTP server and be able to receive this request. The decoding will be done by the HTTP framework/module.

Related

How to retrieve certain data in string?

Hello may i know how to retrieve data in string?
$url = 'test url';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$info = curl_getinfo($ch);
$response = curl_exec($ch);
curl_close ($ch);
echo 'Response: ';
echo gettype($response);
echo '<br>';
echo($response);
Output :
Response: string
TRANSACTION_ID=abc123
MERCHANT_ACC_NO=M213213
TXN_STATUS=A
TRAN_DATE=2020-07-20
CAPTURE_DATE=2020-07-20
SALES_DATE=2020-07-20
RESPONSE_CODE=1
RESPONSE_MESSAGE=Success
As you can see the output of the code is as shown above. This is my first time to encounter this kind of output because usually I get json as the output. So my question is may I know how to retrieve the RESPONSE_MESSAGE in the output or may I know how to convert the output to array or json so that I can easily retrieve the data. Sorry for asking this I'm quite new with this PHP and CURL function.
You can explode to lines and explode the lines to parts in a foreach.
Edit: I realized the "Response:" was actually outputted manually.
Changed the code to slice the array from second item instead.
foreach(array_slice(explode("\n", $str), 1) as $line){
$temp = explode("=", $line);
$res[$temp[0]] = $temp[1];
}
Output:
array(8) {
["TRANSACTION_ID"]=>
string(6) "abc123"
["MERCHANT_ACC_NO"]=>
string(7) "M213213"
["TXN_STATUS"]=>
string(1) "A"
["TRAN_DATE"]=>
string(10) "2020-07-20"
["CAPTURE_DATE"]=>
string(10) "2020-07-20"
["SALES_DATE"]=>
string(11) "2020-07-20 "
["RESPONSE_CODE"]=>
string(1) "1"
["RESPONSE_MESSAGE"]=>
string(7) "Success"
}
https://3v4l.org/evdMO

Unable to integrate Azure ML API with PHP

I tried integrating Azure ML API with PHP but unfortunately getting an error in response.
Updated: I have used request response API sending through json response
Below is the response obtained on executing PHP script:
array(1) { ["error"]=> array(3) { ["code"]=> string(11) "BadArgument"
["message"]=> string(26) "Invalid argument provided." ["details"]=> array(1)
{[0]=> array(2) { ["code"]=> string(18) "RequestBodyInvalid" ["message"]=>
string(68) "No request body provided or error in deserializing the request
body." } } } }
PHP Script:
$url = 'URL';
$api_key = 'API';
$data = array(
'Inputs'=> array(
'My Experiment Name'=> array(
"ColumnNames" => [['Column1'],
['Column2'],
['Column3'],
['Column4'],
['Column5'],
['Column6'],
['Column7']],
"Values" => [ ['Value1'],
['Value2'],
['Value3'],
['Value4'],
['Value5'],
['Value6'],
['Value7']]
),
),
'GlobalParameters' => new StdClass(),
);
$body = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '.$api_key, 'Accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = json_decode(curl_exec($ch), true);
//echo 'Curl error: ' . curl_error($ch);
curl_close($ch);
var_dump ($response);
I have followed few examples, still unable to crack it. Please let me know the solution for this.
According to the error information, I think the issue was caused by requesting the ML REST API without correct json body.
I suggest that you can refer to the article "Getting started with the Text Analytics APIs to detect sentiment, key phrases, topics and language" to correctly format your input rows in JSON as the request body and try again.
Hope it helps.
If you can update your question for specifying which ML REST API you used, I think it's very helpful for figuring out the issue.
Expect your update.

Parse json answer from Redmine API with PHP

I'm trying to parse a JSON answer from Redmine API and I don't know how to get to the parts of the array.
Here is the code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://login:password#redmine.server/redmine/issues.json?cf_2=12345');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$data = json_decode($response);
When I make a var_dump($data), the answer looks like this:
array(1) { [0]=> object(stdClass)#1853 (14) { ["id"]=> int(96) ["project"]=> object(stdClass)#1852 (2) { ["id"]=> int(68) ["name"]=> string(7) "Test.......
So, when I make a for loop, I would like to access the parts of the array:
foreach($data as $issues){
var_dump($issues["id"]);
}
And so on. Any idea on this?
Stupid me...
The culprit was here:
$data = json_decode($response);
Should be:
$data = json_decode($response,true);
Now I get a proper PHP array.

Regex returning empty strings

I have following code:
preg_match_all('/"([^"]*)"/', $json , $results);
var_dump($json);var_dump($results);die();
At this point a dump of $json has
string(423) "{"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX355_.jpg";[355,266],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX425_.jpg":[425,319],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX466_.jpg":[466,350],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX450_.jpg":[450,338],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL.jpg":[500,375]}"
I’m trying to get the links. I’ve tried json_decode but I get error number 4 which is incorrect syntax. There are no invisible characters in front or after the JSON on the string. Without luck i decided to try to regex my way into it but the above code returns
array(2) { [0]=> array(0) { } [1]=> array(0) { } }
Any help to get the first first would be greatly appreciated.
Ok, as some of you noted this is basically a hack to get it to work no matter what. If you are interested in doing it right here’s the full info:
$ch = curl_init("http://www.amazon.com/gp/product/B00BEL2G4C/ref=s9_wish_gw_d31_g21_i3?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=desktop-1&pf_rd_r=1VPYMKFSFN5BRHD4AD3W&pf_rd_t=36701&pf_rd_p=1970559082&pf_rd_i=desktop");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true );
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt" );
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt" );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0");
$curl_scraped_page = curl_exec($ch);
$html = $html->load($curl_scraped_page);
$json = $html->find('#imageBlock', 0)->children[0]->children[0]->children[1]->children[1]->children[0]->children[2]->children[0]->children[0]->children[0]->children[0]->children[0]->attr['data-a-dynamic-image'];
$json = utf8_encode($json);
var_dump(json_decode($json));var_dump(json_last_error());die();
I know that Amazon has an API but they are annoying and will only let you use it if you are an affiliate and they don’t accept under construction websites as affiliates so I’m just trying to get this out and will change it to the API once site goes live and gets approved for Amazon affiliates.
The URL is actually dynamic, just used a static one for testing purposes.
I would love to find a JSON solution as that would be much cleaner.
Do this -
$parsed = json_decode($json, true);
foreach($parsed as $row=>$value){
echo $row .'<br>';
}
EXAMPLE
Not sure why it isn't working. This works for me:
<?php
$json ='{"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX355_.jpg": [355,266],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX425_.jpg":[425,319],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX466_.jpg":[466,350],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX450_.jpg":[450,338],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL.jpg":[500,375]}';
preg_match_all('/"([^"]*)"/', $json , $results);
var_dump($json);var_dump($results);die();
?>
The output is:
gregp:~ greg$ php ./test.preg.php
string(373) "{"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX355_.jpg":[355,266],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX425_.jpg":[425,319],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX466_.jpg":[466,350],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX450_.jpg":[450,338],"http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL.jpg":[500,375]}"
array(2) {
[0]=>
array(5) {
[0]=>
string(65) ""http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX355_.jpg""
[1]=>
string(65) ""http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX425_.jpg""
[2]=>
string(65) ""http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX466_.jpg""
[3]=>
string(65) ""http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX450_.jpg""
[4]=>
string(57) ""http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL.jpg""
}
[1]=>
array(5) {
[0]=>
string(63) "http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX355_.jpg"
[1]=>
string(63) "http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX425_.jpg"
[2]=>
string(63) "http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX466_.jpg"
[3]=>
string(63) "http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL._SX450_.jpg"
[4]=>
string(55) "http://ecx.images-amazon.com/images/I/51Lg%2Bd4cqRL.jpg"
}
}
Just do a non-greedy match between the "'s
preg_match_all('/"(.*?)"/', $json , $results);
var_dump($json);var_dump($results);die();
So I had to do $json = preg_replace('/"/', '"', $json); before calling the decode and that fixed my issue.

How to return this XML-RPC response in an array using PHP?

I'm trying to put together a WordPress plugin and I want to grab a list of all categories (of other WordPress blogs) via XML-RPC. I have the following code and it looks like it works so far:
function get_categories($rpcurl,$username,$password){
$rpcurl2 = $rpcurl."/xmlrpc.php";
$params = array(0,$username,$password,true);
$request = xmlrpc_encode_request('metaWeblog.getCategories',$params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $rpcurl2);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$results = curl_exec($ch);
$res = xmlrpc_decode($results);
curl_close($ch);
return $res;
}
If I use $res I get the following string as the response: Array
If I use $results then I get:
categoryId17 parentId0 descriptionTest categoryDescription categoryNameTest
htmlUrlhttp://test.yoursite.com/?cat=17 rssUrlhttp://test.yoursite.com/?feed=rss2&cat=17
categoryId1 parentId0 descriptionUncategorized categoryDescription
categoryNameUncategorized htmlUrlhttp://test.yoursite.com/?cat=1
rssUrlhttp://test.yoursite.com/?feed=rss2&cat=1
I need to pull out the names after description so Uncategorized and Test in this case.
It's my first time coding in PHP. I got these results by echoing them to the page, so not sure if they get changed in that process or not...
By the way I modified the above code from one that posts to a WordPress blog remotely so maybe I haven't set some of the options correctly?
With var_dump($res) I get:
array(2) { [0]=> array(7) { ["categoryId"]=> string(2) "17" ["parentId"]=> string(1)
"0" ["description"]=> string(4) "Test" ["categoryDescription"]=> string(0) ""
["categoryName"]=> string(4) "Test" ["htmlUrl"]=> string(40)
"http://test.youreventwebsite.com/?cat=17" ["rssUrl"]=> string(54)
"http://test.youreventwebsite.com/?feed=rss2&cat=17" } [1]=> array(7) {
["categoryId"]=> string(1) "1" ["parentId"]=> string(1) "0" ["description"]=>
string(13) "Uncategorized" ["categoryDescription"]=> string(0) "" ["categoryName"]=>
string(13) "Uncategorized" ["htmlUrl"]=> string(39) "http://test.youreventwebsite.com/?cat=1"
["rssUrl"]=> string(53) "http://test.youreventwebsite.com/?feed=rss2&cat=1" } }
You need to iterate your array:
foreach($res as $item) {
echo $item['description'] . $item['categoryName'] . $item['htmlUrl']; //etc...
}

Categories