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.
Related
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
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.
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.
So i have a small PHP script to generate short links, it work but some times i got this error :
Undefined property: stdClass::$id","file":ShortLink.php","line":31
This is my script :
<?php
class ShortLink {
public static function generateShortLink($longUrl)
{
//This is the URL you want to shorten
$apiKey = 'MY_API_KEY';
//Get API key from : http://code.google.com/apis/console/
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
//change the response json string to object
$json = json_decode($response);
curl_close($curlObj);
return $json->id;
}
}
When i start worked with this script 6 or 7 months ago i hadn't this error but now i start get it and i have no idea why, so please if someone has any idea i will be very appreciative.
Update :
When i vardump my $json i get that :
{ ["domain"]=> string(11) "usageLimits" ["reason"]=> string(26) "userRateLimitExceededUnreg" ["message"]=> string(40) "User Rate Limit Exceeded. Please sign up" ["extendedHelp"]=> string(36) "https://code.google.com/apis/console" } } ["code"]=> int(403) ["message"]=> string(40) "User Rate Limit Exceeded. Please sign up" }}
So i wondered if Google limited the Google shorten service ?
class ShortLink {
public static function generateShortLink($longUrl)
{
//This is the URL you want to shorten
$apiKey = 'YOUR_SERVER_API_KEY';
//Get API key from : http://code.google.com/apis/console/
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
//change the response json string to object
$json = json_decode($response);
curl_close($curlObj);
if(!is_object($json))
{
return(false);
}
return $json->id;
}
}
$api = new ShortLink();
$shorturlid=$api->generateShortLink('http://avecsrthgdgnb.avcd');
echo $shorturlid;
are you using new console then enable URL Shortener API.
Sometimes because of network curl is not returned with response within 30 seconds (default time limit in php for a cmd to finish)
Try changing the time limit in php.ini or if that is not in your control or you do not want to modify it for all the php cmds try bool set_time_limit ( int $seconds ) before calling curl_exec
Update:
I see there is no id field in the json that is returned.
{ ["domain"]=> string(11) "usageLimits"
["reason"]=> string(26) "userRateLimitExceededUnreg"
["message"]=> string(40) "User Rate Limit Exceeded. Please sign up"
["extendedHelp"]=> string(36) "https://code.google.com/apis/console"
}
}
["code"]=> int(403)
["message"]=> string(40) "User Rate Limit Exceeded. Please sign up"
}
}
And if you closely see your User rate limit has been reached See here for details on limitation on using google apis. (You may try different IP i.e. different machine or different api key and same code may start working).
Hope this helps
I am using cURL to get json information from a site that pulls a random tumblr picture from a list of sources and I am interested of putting the json data retrieved into php variables so I can call for example, just the image url
$url = "http://someurl.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$a = curl_exec($ch);
$json = var_dump(json_decode($a, true));
I get:
array(3) {
'image' =>
array(1) {
[0] =>
string(62) "http://picture.jpg"
}
'source' =>
string(31) "http://source.tumblr.com"
'page' =>
string(9) "/page/164"
}
What would I now do in order to just print the url for the image?
I have tried
$url = $json["image"][0];
and then calling $url, but it gives me nothing in return. What I am doing wrong?
I have never worked with json before so I am at a loss here, any help is appreciated!
according to code looks:-
try
change
$json = var_dump(json_decode($a, true));
to
$json = json_decode($a, true);