How to merge cURL responses into one array? - php

I'm calling a function to get data from 3 different sources.
The $returnedData response is always an array. How to merge all 3 responses into one array?
function getData($xPostURL,$xToken,$xTokenSecret,$xAccount)
{
$datatopost = array (
"token" => $xToken,
"tokenSecret" => $xTokenSecret,
"account" => $xAccount,
);
$ch = curl_init ($xPostURL);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returnedData = curl_exec ($ch);
echo $returnedData;
}
getData("http://www.example.com/foo.php","","","");
getData("http://www.example.org/bar.php","","","");
getData("http://www.example.net/helloworld.php","","","");

Try use: array_merge
$a = getData("http://www.example.com/foo.php","","","");
$b = getData("http://www.example.org/bar.php","","","");
$c = getData("http://www.example.net/helloworld.php","","","");
$r = array_merge($a,$b,$c);

You can merge Arrays with this function http://php.net/manual/en/function.array-merge.php
If wel use this function your code will look something like this:
function getData($xPostURL,$xToken,$xTokenSecret,$xAccount)
{
$datatopost = array (
"token" => $xToken,
"tokenSecret" => $xTokenSecret,
"account" => $xAccount,
);
$ch = curl_init ($xPostURL);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$returnedData = curl_exec ($ch);
return $returnedData;
}
$firstData = getData("http://www.example.com/foo.php","","","");
$secondData = getData("http://www.example.org/bar.php","","","");
$thirdData = getData("http://www.example.net/helloworld.php","","","");
$merged = array_merge($firstData, $secondData, $thirdData);
Now everything is in $merged
(Also did some indenting and changed echo $returnedData; to return $returnedData; echo only displays it, return returns it to the variable.

Related

JSON Encode To PHP Variable via Curl fails with empty response

i have searched a lot on google and here but im not getting any further with my problem. I am not a coder though I am trying to parse JSON to PHP Variables, but i get an empty response, where i want a table to be shown or at least any jsondata
Here is what my code looks like:
<!DOCTYPE html>
<html>
<body>
<h1>Available Agents </h1>
<?php
$url = 'https://url/livewebservice/imoscontactagentstate?Username=username&Pwd=password&Cmd=GetState&ResultType=JSON';
// Initiate curl
$ch = curl_init ($url);
$data = json_encode ($data,true);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array (
' Content-Type: application/x-www-form-urlencoded ',
'charset=utf-8')
);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
var_dump(json_decode($result, true));
print_r($result);
foreach ($result as $key => $value)
{
echo ' <td><font face="calibri"color="red">'.$value[type].' </font></td><td><font face="calibri"color="blue">'.$value[category].' </font></td><td><font face="calibri"color="green">'.$value[amount].' </font></tr><tr>';
}
echo "</tr></table>";
?>
</body>
</html>
I am grateful for any hints
Try to remove true from $data = json_encode ($data,true); as far as can i remember true is used only in json_decode to create an associative array
The problem was solved my Username did not have the permission to access the data and we made minor changes to the code so it looks like this:
php
$data = array(
"UserName" => "Username",
"Pwd" => "Password",
"Cmd" => "GetAgentStateList",
"ResultType" => "JSON",
);
$url='https://host/livewebservice/service/?'.http_build_query($data);
echo $url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded", "charset=UTF-8",));
$result = curl_exec($ch);
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
curl_close($ch);
$f_result=json_decode($result);
print_r($f_result);
?>
i hope this helps someone coming from google someday.

cURL and ASP.NET : issue with post parameters

We have one search engine which was programed in asp.net.
I manage to curl individual results as they have a more or less direct link that I can predict and curl.
But I don't manage to curl the result list, here is how it works :
On the search page we have to select the database we want to search via a checkbox menu.
Once I check the db I want to search, I click on "Search" button which forwards me to the search page taking the db chosen in consideration.
If I try to go to the search page with a direct link, it doesn't work as it does not know in which db the search will be.
I tried to look at the post parameters with Firebug and I got the following :
Checkbox_db1 on
__EVENTARGUMENT
__EVENTTARGET LinkButtonCategory
__VIEWSTATE zeyhbf5vg41g6a4f1ezragf136er46ga4gfv658a4r6g4 (something looking like that but longer)
Here is what I try in curl :
$ch = curl_init();
$fields = array ('Checkbox_db1' => 'on', '__EVENTARGUMENT' => '',
'__EVENTTARGET' => 'LinkButtonCategory', '__VIEWSTATE' => '');
$postvars = '';
foreach($fields as $key=>$value)
{
$postvars .= $key.'='.$value.'&';
}
rtrim ($postvars, '&');
curl_setopt ($ch, CURLOPT_URL, "monsite.com/choosedb.aspx");
curl_setopt ($ch, CURLOPT_POST, count($fields));
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output1 = curl_exec($ch);
$fields2 = array ('TxtBox1' => 'value1', 'Txtbox2' => 'value2', '__EVENTARGUMENT' => '',
'__EVENTTARGET' => '', '__VIEWSTATE' => '');
$postvars = '';
foreach($fields2 as $key=>$value)
{
$postvars .= $key.'='.$value.'&';
}
rtrim ($postvars, '&');
curl_setopt ($ch, CURLOPT_URL, "monsite.com/search.aspx");
curl_setopt ($ch, CURLOPT_POST, count($fields2));
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output2 = curl_exec($ch);
But of course this doesn't work.... and the issue is that I am not familiar at all with ASP.NET :/
Anyone could help ? Thanks in advance
So first you get the initial page with a regular curl get.
Then you have to extract the VIEWSTATE parameter :
$regexViewstate = '/__VIEWSTATE\" value=\"(.*)\"/i';
function regexExtract($text, $regex, $regs, $nthValue)
{
if (preg_match($regex, $text, $regs)) {
$result = $regs[$nthValue];
}
else {
$result = "";
}
return $result;
}
$viewstate = regexExtract($data,$regexViewstate,$regs,1);
And you make up your new post :
$postData = '__EVENTARGUMENT=&__EVENTTARGET=LinkButtonCategory&__VIEWSTATE=';
$postData .= rawurlencode($viewstate).'&TxtBox1=value1&TxtBox2=value2';
curl_setOpt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_URL, $urlLogin);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
$output = curl_exec($ch);

Post data with curl to another server

I try to post some data to another server using curl. The problem is that I get nothing on the other server.
Server1:
$a = $USER->id;
$b = $USER->username;
error_reporting(-1);
$url = 'http://remote_server/a.php';
$data = array(
'cus' => $a,
'cust' => $b
);
$postString = http_build_query($data, '', '&');
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 2);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$post = curl_exec ($ch);
curl_close ($ch);
and on Server2:
<?php
session_start();
var_dump($_POST);
?>
Of course it doesn't work, it gives array(0) {}.
So, how I will see the data on the other server?
To see the actual output of var_dump($_POST) in Server2, you must either :
Server1 side : echo $post variable
Server2 side : write the content of var_dump's result in a file :
ob_start();
var_dump($_POST);
$output = ob_get_clean();
$fp = fopen('log.txt', 'a');
fwrite($fp, $output);
fclose($fp);

PHP get value from an array

I have this PHP code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$jsondata = curl_exec($ch);
if (curl_error($ch))
die("Connection Error: ".curl_errno($ch).' - '.curl_error($ch));
curl_close($ch);
$arr = json_decode($jsondata);
echo "\nResponse: ".htmlentities($jsondata)."\n\nArray: ".print_r($arr,true);
Which outputs:
Response: {"result":"success","clientid":83} Array:
stdClass Object ( [result] => success [clientid] => 83 )
I want to grab the value 83 stored in the variable called $clientid.
But I can't figure out how to do it.
You are confusing a PHP object with a PHP array.
You should be doing this: echo $arr->clientid;
Example 1, access a value of an object like this:
<?php
$jsondata = '{"firstName":"John", "lastName":"Doe"}';
$arr = json_decode($jsondata);
echo gettype($arr);
echo $arr->firstName;
?>
This prints:
object
John
Example 2, access a value of an array like this:
<?php
$yarr = array(5,6,7);
echo $yarr[0];
?>
This prints:
5
Your main mistake is assuming json_decode returns an array.
$arr = json_decode($jsondata);
Will set up $arr as an object. If you wanted to access it as an array, you can do this:
$arr = json_decode($jsondata, TRUE);
The extra parameter on the end tells json_decode to return an array instead of an object. Then you could do:
echo $arr["clientid"];
try echo $arr["clientid"] to get data from array

json decode into array

I'm trying to store the titles in an array and extract the long cmcontinue string from the below url.
http://en.wikipedia.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:1980_births&format=json
my current code:
$url = 'http://en.wikipedia.org/w/api.php?
action=query&list=categorymembers&cmtitle=Category:'.$cat.'&format=json';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "asdf");
$c = curl_exec($ch);
$json = json_decode($c);
$array = $json->{'query'}->{'categorymembers'}->{'title'};
try adding second paremeter of json_decode, like:
$json = json_decode($c, true);
And get cmcontinue value as:
echo $json["query-continue"]["categorymembers"]["cmcontinue"];
For titles:
$titles = array();
foreach($json["query"]["categorymembers"] as $vals) {
array_push($titles, $vals["title"]);
}
echo "<pre>"; print_r($titles);

Categories