I want to make use of an API but it print alot of info and i don't know how i can get a few key values of the array.
<?php
$query = "SELECT * FROM kvk WHERE adres='Wit-geellaan 158'";
$host = "http://api.openkvk.nl/php/";
$url = $host ."/". rawurlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_exec($curl);
curl_close($curl);
?>
Is my php script and it shows
array(array("RESULT"=>array("TYPES"=>array("int","bigint","varchar","varchar","varchar","varchar","varchar","int","int","smallint","smallint","int"),"HEADER"=>array("id","kvk","bedrijfsnaam","adres","postcode","plaats","type","kvks","sub","bedrijfsnaam_size","adres_size","verhuisd"),"ROWS"=>array(array("1303095","271242250000","Schoonmaakbedrijf Regio","Wit-geellaan 158","2718CK","Zoetermeer","Hoofdvestiging","27124225","0","23","16","0")))))
Thanks in advance
Greetings,
Vierri
//Use the cURL setting to put the result into a variable rather than printing it
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//store the result rather than print (as we set CURLOPT_RETURNTRANSFER)
$result = curl_exec($curl);
if ( $result === false ){
//something went wrong, handle the error
}
//evaluate the array result and store it. (Please don't use this line in production code)
//as the $result string is from a untrusted source
eval('$array = '.$result.';');
//then you can, for example, get a list of the types
$types = $array[0]['RESULT']['TYPES'];
//or some keys
$keys = array_keys($array[0]['RESULT']);
The above code is dangerous and probably shouldn't be used as it is. They could put anything nasty in the response and you would evaluate it (the eval line) which could do bad things to your server. I would check if they have a better API that doesn't send responses in that format. (json or XML would be better)
If not you may want to considerer manually parsing the response array rather than using eval
To get all keys and values:
$server_output = curl_exec($curl);
var_dump($server_output);
To just get a list of keys:
$server_output = curl_exec($curl);
ksort($server_output);
foreach ( $server_output AS $key => $val ) {
echo "$key\n";
}
Related
I want to send data from server 1 to server 2, first I select necessary data from the database, but how to send data with curl? I understand that I cannot send $result parameter just like in my code, but how should I do this?
My Code server 1:
public function setDivisions(){
$result = $this->conn->query("SELECT *FROM data_divisions");
$ch = curl_init('https://example.com/api.php?siteid='.$this->site_key.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $result);
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
print_r($response);
}
Code on server 2:
$array = $_POST['result'];
//loop throw array and insert data into database
you can use it that way.
$ch = curl_init('https://upxxx.cod3fus1ontm.com/curl/json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));
$response = curl_exec($ch);
var_dump($response);
on receipt, like this!
$json = file_get_contents("php://input");
$content = json_decode($json, true);
$records = json_decode($content['records'], true);
foreach($records as $record) {
echo $record['id'] . " - " . $record['text'] . "<br/>";
}
remember, that as you did to encode, you will have to do to decode
Come on, php://input returns all raw data after the request's HTTP headers, regardless of content type.
When we do this with file_get_contents (which reads the contents of a file and puts it into a variable of type string), we can read the content that was sent by curl.
Reviewing the code, you can optimize as follows, when sending to the server you placed, I suggested:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));
you can replace it with:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($result));
it's much simpler, but it's very important to put the query result inside a json_encode
finally, you can access the entire body of the message, through file_get_contents ("php://input") and put it inside a variable, which is nothing more than a JSON of the your query.
for you to understand how the parameters were passed, it is interesting to do the following:
$json = file_get_contents("php: // input");
var_dump($json); <- Here you see the thing as it is.
$records = json_decode($json, true); <- Here you generate an object with the content of json
var_dump($records);
With that, I think that solves the situation.
on server 1
$result = "result=".base64_encode($result)
curl_setopt($ch, CURLOPT_POSTFIELDS, $result);
...
on server 2
$array = base64_decode($_POST['result']);
First of all, I am new in programming. I want to request specific data from another server (data from MSSQL) and transfer (insert) into my MySQL DB, what's the proper way to gain this purpose?
PURPOSE:
A member from MSSQL side would like to transfer certain amount of
points to MySQL, member could input how much of points they had, once
the points is transfer into MySQL successful, a notify script would
send to MSSQL side for update in their end.
What should be generate on MSSQL end, so that MySQL can get these data for further processing?
For example, I have HTTPS link: https://www.example.com/request-transfer.aspx?id=12345&sym=hello&name=linda
For PHP processing end, how can I use cURL to get these data?
I have below script for test, isn't enough to just use $_GET?
// GET
$id = $_GET['id'];
$sym = $_GET['sym'];
$name = $_GET['name'];
$data = array("id" => $id, "sym" => $sym, "name" => $name);
$data_string = json_encode($data);
$ch = curl_init('http://localhost/test/process.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$input = json_decode($data_string);
echo $input->id.', '.$input->sym.', '.$input->name;
echo $result;
Please advise.
You code looks ok so far, just don't set the headers. They will be set automatically on GET/POST requests. Only on PUT requests you need to specify them.
You could JSON stringify the $_GET array directly. This would allow any parameters to be sent to the remote site. If you want to ensure only valid parameters may be sent, you have done it correct. You just should test if the GET parameter is actually present.
If you do not want repeated long expressions, you could write a short function:
function _GET()
{ $n = func_num_args();
for($i = 0 ; $i<$n ;)
{ $key = func_get_arg($i++);
$array[$key] = isset($_GET[$key]) ? $_GET[$key] : '';
}
return $array;
}
$data_string = json_encode(_GET('id', 'sym', 'name'));
Was wondering how i'd be able to extract the index part of the json in php.
Has been bugging me for ages. Thanks!
$ch = curl_init('https://domain.com/blah/blah');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$promo = curl_exec($ch);
curl_close($ch);
$promo = json_decode($promo, true);
.
{"something":"blahhhh","name":"bob!","id":"7","select":[{"Index":1,"code":"a1","name":"hello","description":"more text"},{"Index":2,"code":"a2","name":"bye","description":"test.."},{"Index":3,"code":"a3","name":"ayeee","description":"Morning!"},{"Index":4,"code":"a4","name":"Cheese!","description":"Yummy!"},{"Index":5,"code":"a5","name":"Water","description":"why is it cloudy? :( "}],"chant":"Free the ducks!","joined":"2015-01-01T16:49:05.000+0000","cool":false}
When the 2nd parameter of json_decode is set to true the function return an associative array who's really close to the structure of the JSON.
From there all what you got to do is put back the JSON path into an associative php array to access the wanted value !
foreach($promo['select'] as $select){
echo $select['Index'].' ';
}
example : http://codepad.org/OMg7WTr0
If you're looking to extract other value and you don't figure out the path just do var_dump($promo); it will give you a clear view of the array path to use
From following two files I am getting output (2000)1 but It should only (2000)
After getting value using curl extra 1 is appending, but why?
balance.php
<?php
$url = "http://localhost/sms/app/user_balance.php";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 2);
curl_setopt($ch,CURLOPT_POSTFIELDS, "id=2&status=Y");
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
user_balance.php
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("sms",$conn);
$user_id = $_REQUEST["id"];
$sql = "SELECT * FROM user_sms WHERE user_id='$user_id'";
$rec = mysql_query($sql);
if($row = mysql_fetch_array($rec)) {
$balance = $row["user_sms_balance"];
}
echo "(".$balance.")";
?>
From the PHP manual documentation for curl_setopt():
CURLOPT_RETURNTRANSFER - Set value to TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
If you don't set CURLOPT_RETURNTRANSFER option to TRUE , then the return value from curl_exec() will be the boolean value of the operation -- 1 or 0. To avoid it, you can set CURLOPT_RETURNTRANSFER to TRUE, like below:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
I can see that last response to this question was made back in 2017....
I have bashed my head around for past day and I finally got the results that I wanted. I had the same problem as the author of this question.
Maybe my solution will help others and if do help please vote it I would appreciate it.
So in my case I have build the plugin and using shortcode and cURL API get I am feeding API data into the shortcode output.
Anyway I had this working but also printing the Extra value , which is the true value from the CURLOPT_RETURNTRANSFER.
I have solved this by passing ob_start() and ob_get_clean() inside of my shortcode function. This has cleaned and return the response that I wanted without the Extra value 1 appending at the end of my data response.
My shortcode function looks like this
function shortcode_init(){
ob_start();
include PLUGIN_URL . 'templates/shortcode.php';
return ob_get_clean();
}
As you can see I am including the additional php where my cURL API call is defined.
In case someone needs this..here you go.
$ch = curl_init();
$url = YOUR API END POINT URL HERE;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
echo $err;
} else {
// this returns the array from object
// then we can easily iterate thought arrays and echo values that we need,
$decoded = json_decode($response, true);
}
As mentioned in my previous question I read about cURL and how to work with it. I got the request with the following API: api.openkvk.nl (it's in Dutch, sadly enough) working:
$get = $_POST['bedrijfsnaam'];
$get = str_replace(" ","%20",$get);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.openkvk.nl/php/SELECT%20*%20FROM%20kvk%20WHERE%20bedrijfsnaam%20=%20'$get'%20LIMIT%201;");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
print("<pre>"); print_r($result); print("</pre>");
$kvks = $result[0]["RESULT"]["ROWS"][0][2];
echo $kvks;
curl_close($ch);
and I got the results back in the following form:
array(array("RESULT"=>array("TYPES"=>array("bigint","varchar","int","int","varchar","varchar","varchar","varchar","varchar","varchar","bigint","varchar","decimal","decimal","date"),"HEADER"=>array("kvk","bedrijfsnaam","kvks","sub","adres","postcode","plaats","type","status","website","vestiging","rechtsvorm","lat_rad","lon_rad","anbi"),"ROWS"=>array(array("526937320000","Unicmedia","52693732","0","Terschellingstraat 12","1825ND","Alkmaar","Hoofdvestiging",NULL,NULL,"22611126",NULL,NULL,NULL,NULL)))))
What I want to do is the following:
Put this values from the database: kvks, adres, postcode and plaats in a form (so that I can edit them).
I don't know how to do this. Could you give me an explanation?
PS I'm new with API's so I don't understand everything yet.
Update:
Their API is returning it as a php string - change the part of your URL which says /php/ to /json/.
Then, make it so you have $result = json_decode(curl_exec($ch), true);
Now the array access should work.
To get the value of kvks, supposing the value you posted is the in $result, you'd use $kvks = $result[0]["RESULT"]["ROWS"][0][2].
(It looks like you're posting the result of a print_r - try encasing it in <pre> tags when you display it for a much more formatted result)
Since you have PHP getting the values, you could simply output an HTML form with them prefilled:
<form action="savedata.php" method="post">
<?php
echo "<input type='text' name='blah' value=\"" . htmlspecialchars($blah) ."\"><br>";
?>
Then, if $blah is asdf, this would output <input type='text' name='blah' value="asdf">.
When you submit it to your savedata.php method, you'd insert the modified values (now found through $_POST['blah']) into your database however you like.
From my experiments it seems this API is returning PHP code, this would have to be eval'd. eval is a very bad idea.
Can I suggest using the JSON method of the API instead, by replacing the /php/ with /json/
The API will then return a JSON string which you can decode into an object / array
You will also need to add curl_setop($ch, CURLOPT_RETURNTRANSFER,0); to your curl request
Here is some revised code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.openkvk.nl/json/SELECT%20*%20FROM%20kvk%20WHERE%20bedrijfsnaam%20=%20'$get'%20LIMIT%201;");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
curl_close($ch);
$apiResult = json_decode($result, true);
$apiResult will now contain an array with your result
A var_dump($apiResult) will give you
array
0 =>
array
'RESULT' =>
array
'TYPES' =>
array
...
'HEADER' =>
array
...
'ROWS' =>
array
...
Now that you have the array, you should easily be able to insert it into a DB.