Results from an cURL request into a form - php

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.

Related

Sending array using curl

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']);

using json data from Curl response

Hi I'm a little new at CURL, but I'm trying to request some json data and then parse the results. I am having success with retrieving the data, but I can't handle the response. Here's the code
function bitBucketCurl($url)
{
global $bitPassword;
global $bitUsername;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$bitUsername:$bitPassword");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$commitinfo = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
return $commitinfo;
}
$json = bitBucketCurl($url);
echo $json; // This seems to work in that, when I load the page, I can see the json data
//turn json data into an array - this is what does not seem to be working
$obj_a = json_decode($json, true);
print_r ($obj_a); //the result is simply a 1 rather than the array I would expect
The basic problem is the json data shows up when I echo $json but when I try to turn that data into an array it doesn't work. When I print the array, I just get a '1'.
I got the required result by adding the following line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

Scraping a Webpage for Results Using PHP cURL - Post Not Working

I'm new to using cURL, but from what I have read, the following should post the variables to the page, then print the result. The result prints, but it doesn't seem like the POST variables went because no results are generated. FireBug doesn't show anything going either. Any ideas what I'm doing wrong?
Thanks for your help!
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://butlercountyclerk.org/bcc-11112005/ForeclosureSearch.aspx");
$data = array(
'Search:btnSearch' => 'Search',
'Search:ddlMonth' => '1',
'Search:ddlYear' => '2011'
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
echo $output;
Based on the coding of the site, it appears that you're missing a number of variables. Take for example, the actual post request made to the search page:
__VIEWSTATE=dDwtMjk2Mjk5NzczO3Q8O2w8aTwxPjs+O2w8dDw7bDxpPDE+Oz47bDx0PDtsPGk8Mz47aTwxOT47PjtsPHQ8dDw7cDxsPGk8MD47aTwxPjtpPDI+O2k8Mz47aTw0PjtpPDU+Oz47bDxwPDIwMDY7MjAwNj47cDwyMDA3OzIwMDc+O3A8MjAwODsyMDA4PjtwPDIwMDk7MjAwOT47cDwyMDEwOzIwMTA+O3A8MjAxMTsyMDExPjs+Pjs+Ozs+O3Q8QDA8Ozs7Ozs7Ozs7Oz47Oz47Pj47Pj47Pj47PmVlaXw5JK161vti9TC+QMdeTNQI&Search:ddlMonth=1&Search:ddlYear=2011&Search:txtCompanyName=&Search:txtLastName=&Search:txtCaseNumber=&Search:btnSearch=Search
This is post-feeding though URLDecode by the way. What this means though, is that your array of 3 values is missing data. At the very least, I'd suspect that Search:btnSearch=Search is missing, and would suggest that you implement all fields into your POST request.

how to get key value of array with curl (php)

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";
}

PHP return value from decoded object

Can someone please tell me where is the error in this code?, I use a mobile iphone application to call a php script tha will send information to apple. Apple then will return a JSON object containing several values in an associative array.
I want to reach the 'status' value but every time I run the code in the phone, the php script sends me the complete apple's returned string. In the XCode debugger the received string looks like:
[DEBUG]... responseString :
{"receipt":{"item_id":"328348691",
"original_transaction_id":"1000000000081203",
"bvrs":"1.0", "product_id":"julia_01",
"purchase_date":"2009-10-05 23:47:00
Etc/GMT", "quantity":"1",
"bid":"com.latin3g.chicasexy1",
"original_purchase_date":"2009-10-05
23:47:00 Etc/GMT",
"transaction_id":"1000000000081203"},
"status":0}
but the only piece I care in the string is the "status" value.
I've already looked inside documentation but can't find the solution. I'm new in php but this getting too long. Here the script:
<?php
//The script takes arguments from phone's GET call
$receipt = json_encode(array("receipt-data" => $_GET["receipt"]));
//Apple's url
$url = "https://sandbox.itunes.apple.com/verifyReceipt";
//USe cURL to create a post request
//initialize cURL
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
// howmany parameter to post
curl_setopt($ch, CURLOPT_POST, 1);
// the receipt as parameter
curl_setopt($ch, CURLOPT_POSTFIELDS,$receipt);
$result = curl_exec ($ch);
//Here the code "breaks" and return the complete string (i've tested that)
//and apparently doesn't get to the json_decode function (i think something's wrong there, so code breaks here)
curl_close ($ch);
$response = json_decode($result);
echo $response->{'status'};
?>
Even if I don't put any echo at the end, the script still returns a complete string (odd to me)
Thank's in advance and apollogies if I insist again from another question
Try setting the RETURNTRANSFER option to 1 so you can capture the output from the requested URL as a string. It seems that the default behaviour of cURL is to output the result directly to the browser:
...
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
// howmany parameter to post
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // <---- Add this
// the receipt as parameter
curl_setopt($ch, CURLOPT_POSTFIELDS,$receipt);
...

Categories