I'm trying to get data trough a JSON API from Groove.
https://www.groovehq.com/docs/tickets#listing-tickets
and https://www.groovehq.com/docs
This is the code I made:
<?php
function timjson_front($atts, $content) {
global $wpdb;
$access_token = ""; //insert token
$user_email = ""; // insert customers email
$json = getJSON($access_token, $user_email);
$html = "";
foreach($json as $key => $waarde) {
$html .= $key . ' = ' . $waarde;
}
return html_entity_decode($html);
}
function getJSON($access_token, $user_email) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.groovehq.com/v1/tickets?acces_token=' . $access_token . '&customer=' . $user_email);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
return $obj;
}
?>
The code runs on a wordpress page and is part of a self made plugin. The idea is that the tickets from a customer gets printed on a page.
Wordpress gives a error at foreach(). Does anyone know what i'm doing wrong? Or has some advice?
First
You're iterating on $obj but $obj = json_decode($result); will returns an object. You need to iterate through an array so use json_decode($result, true)
Second
Based on the API, the first key is tickets and has multiple tickets
So you want to start with tickets in the foreach:
foreach($json['tickets'] as $ticket){
foreach($ticket as $key => $waarde) {
$html .= $key . ' = ' . $waarde;
}
}
Third
You're concatenating strings with $html .= $key . ' = ' . $waarde;
But based on the API, the values are not ALWAYS strings.
foreach($json['tickets'] as $ticket){
foreach($ticket as $key => $waarde) {
if(!in_array($key, ['tags','links'])){ // ignore the keys "tags" and "links" because they are array
$html .= $key . ' = ' . $waarde;
}
}
}
Edit: POC https://3v4l.org/dblmj
Related
I need to get JSON data from this website : https://shopee.co.id/search?keyword=western%20digital
I've tried and get this result: https://shopee.co.id/api/v2/search_items/?by=relevancy&keyword=western%20digital&limit=50&newest=0&order=desc&page_type=search
That's fine until I noticed the price is null and I need that price value
Any other method? Maybe I'm doing it wrong
Code so far:
<?php
function http_request($url){
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
// set user agent
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
//close curl
curl_close($ch);
echo $output;
// return output
return $output;
}
if (isset($_POST['find']))
{
$search = $_POST['text_value'];
$search = str_replace(' ', '%20', $search);
$url = "https://shopee.co.id/api/v2/search_items/?by=relevancy&keyword=western%20digital&limit=50&newest=0&order=desc&page_type=search";
$profile = http_request($url);
// JSON to Array
$profile = json_decode($profile, TRUE);
$i = 0;
foreach($profile["data"] as $profil){
//add name, price from json
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Curl Data JSON</title>
</head>
<body>
<form action = "index2.php" method = "POST">
<input type = "text" name="text_value"><input type = "submit" value = "search" name = "find">
</form>
</body>
</html>
Hello I'm new in laravel and have some strange situation:
in laravel api.php I have route
Route::get('/blog', function() {
$url_query_string = "format=json";
$request_url = 'https://www.squarespace.com/templates/?' . $url_query_string;
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_USERAGENT, 'H.H\'s PHP CURL script');
$response_body = curl_exec($ch);
curl_close($ch);
$res = json_decode($response_body,true);
echo json_encode($res);
});
so it is working but not gives me validated json it is not correct look at picture
not sure where is a problem?
I fixed this adding header('Content-Type: application/json');
$res = json_decode($response_body,true);
header('Content-Type: application/json');
echo json_encode($res);
Just add this small piece of code
if($request->isJson()) {
if(empty($request->json()->all())) {
echo "Invalid Json"
//Put invalid JSON handling functions here
} else {
echo "Valid JSON"
//Put you regular functions here because the input JSON is valid
// Even if you don't put the else clause it is ok the code will continue executing further
}
}
How to get the product details in JSON format using REST API in Magento2? When I search I found the following code.
$url = 'magentohost url';
$callbackUrl = $url . "oauth_admin.php";
$temporaryCredentialsRequestUrl = $url . "oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = $url . 'admin/oauth_authorize';
$accessTokenRequestUrl = $url . 'oauth/token';
$apiUrl = $url . 'api/rest';
$consumerKey = 'consumer_key';
$consumerSecret = 'consumer_secret';
$token = 'token';
$secret = 'token_secret';
try {
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauthClient->setToken($token, $secret);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json', 'Accept' => 'application/json'));
$productsList = json_decode($oauthClient->getLastResponse());
echo '<pre>';
print_r($productsList);
}
catch(Exception $e) {
echo '<pre>';
print_r($e);
}
But where I need to put this query... And also I am confusing with the URL...
And also it returns error Class OAuth not found
First, we need to create Web Service Role and Web Service User in Magento 2
Create Web Service Role:
Login Admin Panel> System> User Roles> Add New Role
Add the Role Name and your current password of Admin in Your Password field
Tap Role Resources
Choose what are required for service of your web in Resource Access
Tap Save Role
Create Web Service User in Magento 2
This user is used for the role you’ve created
Go to System> All Users> Add New User
Fill in all the necessary information
Tap User Role then choose which you’ve created
Tap Save User
The user above will used to REST API web service in Magento 2.
Next, we will get starting with Magento 2 REST API. Create a php file called my_magento2_rest_apt.php or whatever you want to make it. and place it in the magneto root directory.
Add this code into the file.
define('BASEURL','http://yourdomin.com/magento2location/');
$apiUser = 'username';
$apiPass = 'password';
$apiUrl = BASEURL.'index.php/rest/V1/integration/admin/token';
/*
Magento 2 REST API Authentication
*/
$data = array("username" => $apiUser, "password" => $apiPass);
$data_string = json_encode($data);
try{
$ch = curl_init($apiUrl);
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))
);
$token = curl_exec($ch);
$token = json_decode($token);
if(isset($token->message)){
echo $token->message;
}else{
$key = $token;
}
}catch(Exception $e){
echo 'Error: '.$e->getMessage();
}
/*
Get Product By SKU REST API Magento 2
Use above key into header
*/
$headers = array("Authorization: Bearer $key");
//$requestUrl = BASEURL.'index.php/rest/V1/products/24-MB01';//24-MB01 is the sku.
//$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria[page_size]=10';// get total 10 products
//$requestUrl = BASEURL.'index.php/rest/V1/categories/24/products';// 24 category id
//$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria=';//get all products
$requestUrl = BASEURL.'index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=24&searchCriteria[filter_groups][0][filters][0][condition_type]=eq';
$ch = curl_init();
try{
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
if(isset($result->message)){
echo $result->message;
}else{
print_r($result);
}
}catch(Exception $e){
echo 'Error: '.$e->getMessage();
}
now to get to your API just type. http://yourdomin.com/magento2location/my_magento2_rest_apt.php
<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
break;
}
}
return $country();
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
echo $country('$capital');
echo $country('$currency');
echo $country('$region');
?>
I followed this post - https://stackoverflow.com/a/38906191/3939981
If I rewrite the code inside function, it works
<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
echo $capital;
echo $currency;
echo $region;
break;
}
}
return $currency;
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
?>
Maybe some parts of the code did not work..Any comments and thoughs
You could use this code. Note that if you want a function to return three values, you should create an array with those values, and return that array. I also renamed the function, since it does not only return currency information:
function getCountryInfo($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
return array(
"currency" => $country->currency[0],
"capital" => $country->capital,
"region" => $country->region
);
}
}
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$country = getCountryInfo($arr, "Aruba");
echo $country['capital'] . "<br>";
echo $country['currency'] . "<br>";
echo $country['region'] . "<br>";
I am building a Live Search function on my website, I used the W3schools example, which worked perfectly. But I want to use MySQL database instead of the XML file, so I am working on a code to take the MySQL database and turn it into an XML file.
<?php
header("Content-type: text/xml");
include 'dbc.php';
$query = "SELECT * FROM airports";
$result = mysql_query($query, $link)
or die('Error querying database.');
$xml_output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xml_output .= "<entries>\n";
for($x = 0 ; $x < mysql_num_rows($result) ; $x++){
$row = mysql_fetch_assoc($result);
$xml_output .= "\t<entry>\n";
$xml_output .= "\t\t<ident>" . $row['ident'] . "</ident>\n";
// Escaping illegal characters
$row['name'] = str_replace("&", "&", $row['name']);
$row['name'] = str_replace("<", "<", $row['name']);
$row['name'] = str_replace(">", ">", $row['name']);
$row['name'] = str_replace("\"", """, $row['name']);
$xml_output .= "\t\t<name>" . $row['name'] . "</name>\n";
$xml_output .= "\t</entry>\n";
}
$xml_output .= "</entries>";
echo $xml_output;
?>
I am getting this error:
Warning: DOMDocument::load() [domdocument.load]: Start tag expected, '<' not found in /public_html/sql2xml.php, line: 11 in /public_html/livesearch.php on line 12
no suggestion
I have read the explanation at: Avoid DOMDocument XML warnings in php
But I have no idea how to fix that in my code. Any suggestions?
This will take the data from the 'Name' column in your mysql table and put it into an array its the same array w3c school looks up as you type
$mysqli = new mysqli(HOST,USER,PASSWORD,DATABASE);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM table";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{
$a[]=$row["Name"];
}
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
if (isset($q))
{
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
}