I'm new to Laravel. Trying to work with external API.
In controller i wont just to make variable with json:
$testapi = new TestApi();
$data['books'] = $testapi->books();
return view('books.index', $data);
In model (just php class without any extends) this:
public function books()
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->host."/books");
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
$result = curl_exec($curl);
$result = json_decode($result);
curl_close($curl);
return $result;
}
But json content is placed at the beggining of HTML file, even before META information. curl_exec don't save result to variable, but transfer it to global result. How to save this json to variable and then use inside template?
I believe you're missing
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
that will allow the return to be put into your $result variable, instead of outputting directly.
Related
I am using the contact API but it returns maximum 250 contacts only. I used 'vidOffset' parameter for next page but no luck.
Note: I want to export all the contacts from the Hubspot List to my local database using API
Here is my code with php curl:
function callAPI($method, $url, $data){
$curl = curl_init();
$url = $url.'&property=firstname&property=email&count=5&vidOffset=2';
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
return $result;
}
// call the function
callAPI('GET', 'https://api.hubapi.com/contacts/v1/lists/11/contacts/all?hapikey=[API key]', false);
Is there anything wrong I am doing? or if there is a better way to get all contact using php/wordpress then please share your experience.
There are a few things to look for here when you make your calls to this API.
Is there a "true" value in the "has-more" field. If so, there are more contacts that can be pulled.
The value of the "vid-offset" field that is returned in your calls.
For the "has-more", this boolean specifies whether or not there are more contacts that you can pull via pagination. For the "vid-offset", this is an integer generated by the API, it does not take a simple sequential integer.
Additionally, you're only grabbing 5 records at a time, you may as well just do the maximum, since it's only 100. This will limit the number of calls you need to make.
Lastly, you may just want to add these to a file, which you can then use for whatever you want, i.e. adding to database, download etc.
So, my suggestion is to amend your initial function to check for the "has-more" value of "true", if it is true send the "vid-offset" value to a new function that makes another call. In that function, you can continue to check for those values, and run your function as many times as it takes until that "has-more" value turns up false.
// the rest of your function is above
// Decode the result so you can traverse the data
$contacts = json_decode($result);
// Store 'has-more' value
$has_more = $contacts->has-more;
// Check if there are more records
if($has_more) {
// Get the offset number provided by API
$offset = $contacts->vid-offset;
// Get more records
getMore($offset);
} else {
// Complete calls and do something else...
}
}
function getMore($offset) {
// Make cURL call with your your offset value
$url = $url.'&property=firstname&property=email&count=100&vidOffset=' . $offset;
$contacts = json_decode($result);
$has_more = $contacts->has-more;
if($has_more) {
$offset = $contacts->vid-offset;
getMore($offset);
} else {
// Complete calls and do something else...
}
}
The documentation that they provide is actually quite clear, so I would read it over a bit as well.
I have this json object that I want to get the access_token but its refusing i have no idea why . This is the response I want the access_token
{
"access_token": "Alhq74lVl5GAOVAZrprOGSS1Gj73",
"expires_in": "3599"
}
This is the code
function generateToke() {
// $url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
$credentials = base64_encode('qniogqzdbIskIQt9nxgxG1wSBkzgUqN0:XUjxWzQY3WTndqHh');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $credentials)); //setting a custom header
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$result = json_decode($curl_response);
$token = $result->access_token;
echo $token;
}
getting the same error
the above code is still displaying to me the json but i want to get only the Alhq74lVl5GAOVAZrprOGSS1Gj73
You're not accessing the access_token property of the resulting object, you try to access a property that is named in the not defined variable $access_token;.
So just remove the $-sign and it shoudl work:
$token = $result->access_token;
Furthermore you're missing a curl option to return the content:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
Without this option set to true you're not retrieving the response from the curl_exec call.
Change:
$token = $result->$access_token;
To (without the $ on access_token):
$token = $result->access_token;
It's not working because PHP has a feature called variable variables which you've accidentally used. PHP is trying to get the property of whatever the value of $access_token is. E.g. if a variable called $access_token was set to helloworld, PHP would run $result->helloworld and replace $access_token with it's value.
I am working with a API. the link shows in the class like this
private $apiPath = "http://www.website.com/api/v1/users/username";
now if the username part is tom and i put it in the browser like so.
private $apiPath = "http://www.website.com/api/v1/users/tom";
it will display all toms stats in text format.
I am trying to figure out how to display it in HTML rendered format
using php so i can display it on my site. I was told its in an array.
so I am assuming using variables i can get it to display what and where I want. I am just really unclear.
I have the class but unsure what to do. do i include it?
This will allow you to grab the username from db and compare
function stats(){
$user_id = $_GET['uid'];
$sql = "SELECT * FROM users WHERE uid = $user_id ";
$result = query($sql);
$row = mysqli_fetch_object($result);
$username = $row->username);
$url = ('"http://www.website.com/api/v1/users/'.$username);
$rCURL = curl_init();
curl_setopt($rCURL, CURLOPT_URL, $url);
curl_setopt($rCURL, CURLOPT_HEADER, 0);
curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, 1);
$aData = curl_exec($rCURL);
curl_close($rCURL);
$response = json_decode($aData, true);
}
If you just want the data that the API is returning, that class would tell me that it is returning JSON which is a data interchange format. You could use PHP's cURL function to get the data from the API and then decode it into a PHP array using json_decode and then you could do what you like with the data.
For example:
$apiUrl = "http://www.website.com/api/v1/users/$username";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$apiURL);
$result=curl_exec($ch);
curl_close($ch);
$userArray = json_decode($result, true);
If you need to use the class as you need to process the data into the form it does, you will need to include the class and use it.
import 'myclass.php';
$userData = new statsProfile('name');
Then you can use the other methods of the class as you need.
Here is my index.php file...
<?php
// Defining the basic cURL function
function curl($url) {
$ch = curl_init(); // Initialising cURL
curl_setopt($ch, CURLOPT_URL, $url); // Setting cURL's URL option with the $url variable passed into the function
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Setting cURL's option to return the webpage data
$data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable
curl_close($ch); // Closing cURL
return $data; // Returning the data from the function
}
$url1 = $_GET['link'];
$response = curl($url1);
$response = str_replace("./views","http://movietube.pm/views",$response);
$response = str_replace("./lib","http://movietube.pm/lib",$response);
$response = str_replace("./assets","http://movietube.pm/assets",$response);
echo $response;
?>
// Defining the basic cURL function
function curl($url) {
$ch = curl_init(); // Initialising cURL
curl_setopt($ch, CURLOPT_URL, $url); // Setting cURL's URL option with the $url variable passed into the function
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Setting cURL's option to return the webpage data
$data = curl_exec($ch); // Executing the cURL request and assigning the returned data to the $data variable
curl_close($ch); // Closing cURL
return $data; // Returning the data from the function
}
$url1 = $_GET['link'];
$response = curl($url1);
$response = str_replace("./views","http://movietube.pm/views",$response);
$response = str_replace("./lib","http://movietube.pm/lib",$response);
$response = str_replace("./assets","http://movietube.pm/assets",$response);
echo $response;
?>
Basically, what I want it to do is take an input
www.example.com?link=(link)
and return the HTML of the page, after executing the php...
On the output, it loads the page correctly, but it doesn't put in the tv show stuff, like the video player, the links, or the episode director...
What it does...
http://muchmovies.uphero.com/?link=http://www.tvstreaming.cc/watch.php?v=TGmi0OPy0Cc
What I want it to do...
http://www.tvstreaming.cc/watch.php?v=TGmi0OPy0Cc
Any help is appreciated!
Maybe you have a problem with php variable $_GET['link'] because you put this link:
http://muchmovies.uphero.com/?link=http://www.tvstreaming.cc/watch.php?v=TGmi0OPy0Cc
And note that your query string will be this:
?link=http://www.tvstreaming.cc/watch.php?v=TGmi0OPy0Cc
This query string must be encoding and you are not encoding it, so, variable $_GET['link'] will not have the value that you need to do the curl.
I recommend you 2 options:
Encode url params
Or, pass the url using base64 encode then on your
server use base decode
Please, tell me if this was the solution.
I've create a script that will delete all user properties for a particular individual. I'm able to use an api call to get the users' properties from the xml. And I'm using a delete api to remove each property.
I would like to be able to test when there are no more properties left and then output a message accordingly. Inside the for loop is where each property is found. Any help is certainly appreciated.
Below is the code:
<?php
$user_id="john_smith#ourwiki.com";
$url=('http://user:12345#192.168.245.133/#api/users/=john_smith#ourwiki.com/properties');
$xmlString=file_get_contents($url);
$delete = "http://user:12345#192.168.245.133/#api/DELETE:users/$user_id/properties/%s";
$xml = new SimpleXMLElement($xmlString);
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // returns output as a string instead of echoing it
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); // if your server requires basic auth do this
return curl_exec($ch);
}
foreach($xml->property as $property) {
$name = $property['name']; // the name is stored in the attribute
curl_fetch(sprintf($delete, $name),'user','12345');
}
?>
The foreach construct automatically loops until the end of the enumerable object (namely $xml).
I think you're looking for the count function:
if(!count($xml->property)) die('No more properties');