I'm trying to play with a web service via REST.
I finally am getting the results I want (or at least I think I am), but am unaware what to do with it. The response format is JSON.. I try outputting it via json_decode() to get it as an array, then I could do something with it.
You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing
I know this is a matter of education, but this is my first jaunt at this, so any help is appreciated. Again, my end goal is to obviously output the data in a readable format.
<?php
if(isset($_GET['word']))
{
$result= get_response_json($_GET['word']);
} else {$result = "";}
function get_response_json($word)
{
$postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
echo $postURL;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $postURL);
curl_setopt($ch, CURLOPT_HEADER, false);
//curl_setopt($ch, CURLOPT_POST, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
<html>
<title>Test Rhyme</title>
<body>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="get">
<input type="input" name="word" />
<input type="submit" value="Submit" />
</form>
<div id="results">
<?php
print_r(json_decode($result, true));
?>
</div>
</body>
</html>
Check here: http://php.net/manual/en/function.curl-exec.php. The one noteworthy thing I saw was this:
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
Note that there is a great example if you search for "curl_get(".
Here's an example:
$json = '[
{
"ID": "1001",
"Phone": "5555555555"
}
]';
$jsonArray = json_decode($json);
foreach($jsonArray as $value){
$id = $value->ID;
$phone = $value->Phone;
}
Here's a simplified way to do it without cURL
function get_response_json($word)
{
$postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
$json = file_get_contents($postURL);
return $json;
}
Related
I cannot see the details of the product I have selected in my product list with the woocommerce rest api
The main problem is that when I write the id of the product, I see it as json, but I have a problem when I want to include it in an array.
The main problem is that I can't send product id to single_product_connect.php with get_file_content, so it shows $ data array empty
form code;
<form action="single_product.php" name="update" method="get">
<td><input type="submit" name="edit"id="edit" value="<?= $row['id']; ?>"/></td></form>
single_product.php code;
<?php
$data = file_get_contents('http://localhost/api-woocommerce/single_product_connect.php');
$data = json_decode($data, true);
?>
<?php foreach ( $data as $row ) : ?>
<?= $row['id']; ?>
<?= $row['name']; ?> //I wrote a small piece for testing
<?php endforeach; ?>
single_product_connect.php code;
<?php $product_id = $_GET['edit'];?>
<?php echo json_encode($woocommerce->get("products/{$product_id}",$data)); ?>
error screen;
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\api-woocommerce\single_product.php on line 19////The code in line 19:
<?php foreach ( $data as $row ) : ?>
When you use file_get_contents to get single_product_connect.php with http you can pass "edit" as a parameter if you concatenate query parameters to your url.
Try this change:
$id = /*some id*/;
$data = file_get_contents('http://localhost/api-woocommerce/single_product_connect.php?edit='.$id);
As you've mentioned can't send product id to single_product_connect.php with get_file_content so, when you're calling the remote url, the return value is an empty string which on json_decode() becomes null. You can check this by just adding this json_last_error() after json_decode() like this
$data = json_decode($data, true);
$erorr = json_last_error();
var_dump($data);
echo $error;
You can first append the product_id to the url and then can make the call to the url using file_get_contents like this
$url = "http://localhost/api-woocommerce/single_product_connect.php?product_id=<product_id>";
$data = json_decode(file_get_contents($url), true);
but I would suggest you to either use curl (recommended) or fsockopen.
With curl, it's very easy
// create curl resource
$ch = curl_init();
// set url
$url = "http://localhost/api-woocommerce/single_product_connect.php?product_id=<product_id>";
curl_setopt($ch, CURLOPT_URL, $url);
//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);
$data = json_decode($output, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_last_error_msg();
exit();
}
foreach ($data as $row) {
// do something
}
I have to create an simple form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML page</title>
</head>
<body>
<form method="post" action="process.php">
<input type="text" name="firstname" placeholder="rahul_sharma">
<button type="submit">send</button>
</form>
</body>
</html>
From my process.php file, I have to hit an url like below:
https://stackoverflow.com/api?rahul_sharma
which will give back an json response
{"status":"Success","username":"your username is RAHULSHARMA"}
If status is success, have to display the username value.
New to php.Any help is appreciated.
you can call API using curl.
$url='https://stackoverflow.com/api?';
$call_url = $url . $_POST['first_name'] ;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $call_url,
CURLOPT_SSL_VERIFYPEER => false,
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;//{"status":"Success","username":"your username is RAHULSHARMA"}
In your process.php file, you can use the $_POST superglobal to fetch the form data.
$firstname = $_POST['firstname'];
After that you can concatenate it using the . operator to form the url.
$url = "https://your-api-site.com/api?" . $firstname;
Next you can fetch the content from the url using a curl request.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
The result from fetching the url will be obtained in the $output variable. Suppose the result from your API is a JSON string like the one you provided, you can use json_decode PHP function to convert it to an associative array.
$result = json_decode($output);
Now you can use if conditions to check if status is Success and display the username.
if ($result['status'] == "Success") {
echo $result['username'];
}
If you access the webpage https://api.mercadolibre.com/items/MLB752465575 you will receive a JSON response. All I need to start is print the item "id" on the screen.
This is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$json_str = "https://api.mercadolibre.com/items/MLB752465575";
$obj = json_decode($json_str);
echo "id: $obj->id<br>";
?>
</body>
</html>
All I want is receive the MLB752465575 part into my browser.
How can I do it?
$json_str = "https://api.mercadolibre.com/items/MLB752465575";
The above does not retrieve the data it's saving the url to the var and that's not what you want.
You just need to fetch the content You can use cURL or file_get_contents()
cURL version:
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
file_get_contents version:
<?php
$r = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
echo "<pre>";
echo print_r(json_decode($r, true));
echo "</pre>";
?>
Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.
Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.
Use curl to get the result, and json_decode to turn it into an array.
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode != 200) {
echo "error " . $httpcode;
curl_close($ch);
return -1;
}
$result_arr = json_decode($result, true);
echo $result_arr['id'];
curl_close($ch);
$jsonResponse = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
$obj = json_decode($jsonResponse);
echo "id: {$obj->id}<br>";
What you did in your code was to json_decode the URL itself. You needed to get the content from the URL, and then decode the content.
I have a page with a recaptcha in it, and it had been running without any problem for two months. But now, since a few days, it has been acting weird. I have tried many several times, but the captcha is simply not working, the verification part.
Here is the code
$captcharesponse = test_input($_POST["g-recaptcha-response"]);
$status = captcha($captcharesponse);
...
function captcha($t){
$captcharesponse = $t;
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($curl, CURLOPT_POSTFIELDS, 'secret=7...PRIVATE_KEY...S&response=' . $captcharesponse);
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
if($result['success'] == false){
error_log(date("Y-M-d, D h:i:s A") . " : Result = " . $result['success'] . ", and error = " . $result['error-codes']);
}
return $result['success'];
}
And no matter what, even if I am not even entering the captcha, still the page is taking too long, and hence nothing is working. Please not that other things are simply skipped if the captcha is wrong, so there is no way that other things are causing the delay.
Thanks in advance
PS. I am not using any kind or library or anything, and it did use to work some time back without any problem.
The 'test_input()' code:
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The problem has been resolved,
Apparently it was a problem on reCAPTCHA's end. The above provided code is now working flawlessly, and all slow-performance problems have been resolved as well.
Thank you all.
PS. Others can use this code if the want.
I'd say to use the recaptcha library, available at:
https://github.com/google/recaptcha
First of all, download the files, most important is recaptchalib.php (you can download all files clicking the download zip button at right).
Then unzip it to your folder and use it like the example unzipped along (example-recaptcha.php):
<?php
require_once "recaptchalib.php";
// Register API keys at https://www.google.com/recaptcha/admin
$siteKey = "YOURSITEKEY";
$secret = "YOURSECRET";
$lang = "en";
$resp = null; // The response from reCAPTCHA
$error = null; // The error code from reCAPTCHA, if any
$reCaptcha = new ReCaptcha($secret);
if ($_POST["g-recaptcha-response"]) { // Was there a reCAPTCHA response?
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
?>
<html>
<head><title>reCAPTCHA Example</title></head>
<body>
<?php
if ($resp != null && $resp->success) {
echo "You got it!";
}
?>
<form action="" method="post">
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey;?>"></div>
<script type="text/javascript"
src="https://www.google.com/recaptcha/api.js?hl=<?php echo $lang;?>">
</script>
<br/>
<input type="submit" value="test recaptcha" />
</form>
</body>
</html>
I am trying to capture the first instance of particular elements from an object. I have an object $doc and would like to get the values of the following.
id, url, alias, description and label i.e. specifically:
variable1 - Q95,
variable2 - //www.wikidata.org/wiki/Q95,
variable3 - Google.Inc,
varialbe4 - American multinational Internet and technology corporation,
variable5 - Google
I've made some progress getting the $jsonArr string however I'm not sure this is the best way to go, and if so I'm not sure how to progress anyway.
Please advise as to the best way to get these. Please see my code below:
<HTML>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=$search&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
var_dump($doc);
echo "<p>";
$jsonArr = $doc->documentElement->nodeValue;
$jsonArr = (string)$jsonArr;
echo $jsonArr;
}
?>
</body>
</HTML>
Since the response to your API request is JSON, not HTML or XML, it's most appropriate to use cURL or Stream library to perform the HTTP request. You can even use something primitive like file_get_contents.
For example, using cURL:
// Make the request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.wikidata.org/w/api.php?action=wbsearchentities&search=google&format=json&language=en");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
// Decode the string into an appropriate PHP type
$contents = json_decode($output);
// Navigate the object
$contents->search[0]->id; // "Q95"
$contents->search[0]->url; // "//www.wikidata.org/wiki/Q95"
$contents->search[0]->aliases[0]; // "Google Inc."
You can use var_dump to inspect the $contents and traverse it like you would any PHP object.