Getting the Error Message - Notice: Trying to get property of non-object in I'm trying to experiment/learn with the YELP API but I'm getting stuck with a simple error message, I can't seem to figure out. Following this: https://github.com/Yelp/yelp-api/tree/master/v2/php
function query_api($term, $location) {
$response = json_decode(search($term, $location));
$business_id = $response->businesses[0]->id;
print sprintf(
"%d businesses found, querying business info for the top result \"%s\"\n\n",
count($response->businesses),
$business_id
);
$response = get_business($business_id);
print sprintf("Result for business \"%s\" found:\n", $business_id);
print "$response\n";
}
Calling the function
$longopts = array(
"term::",
"location::",
);
$options = getopt("", $longopts);
$term = $options['term'] ?: '';
$location = $options['location'] ?: '';
query_api($term, $location);
This notice indicates that $response is not an object and you are trying to access a property businesses that doesn't exist.
Use var_dump($response) to get information about this variable.
Related
I'm trying to update the Woocommerce Orders with a custom meta data field
On Woocommerce order complete (status change) I have a Invoicing plugin that automatically generates customer invoice documents, this plugin has its own hooks/filters such as:
apply_filters('moloni_after_insert_document', $this);
After it inserts (generates) the invoice, I use their API to return a value ( the invoice code ) that I want to save on that order meta data.
This is the code that I use:
add_action('moloni_after_insert_document', 'save_codigo_at', 10, 4 );
function save_codigo_at( $order_id ) {
// On Order complete > access Moloni API > GETPDFLINK > Sanitize string and get Hash > Get document ID from order >
// Retrieve from the Database table moloni_api the access token from column main_token
global $wpdb;
$table_name = "wp_moloni_api";
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name WHERE id = 1" );
foreach ($retrieve_data as $retrieved_data) {
$maintoken = $retrieved_data->main_token;
}
// Get document ID from the order
$documentid = get_post_meta($order->id, '_moloni_sent', true);
// Connect to moloni API and getpdflink
$url = "https://api.moloni.pt/v1/documents/getOne/?access_token=$maintoken";
$postData = array(
'company_id' => '11111',
'document_id' => $documentid );
$arguments = array(
'method' => 'POST',
'headers' => array(
'Content-type: application/x-www-form-urlencoded'
),
'body' => $postData,
);
$response = wp_remote_post( $url, $arguments );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
return "Something went wrong: $error_message";
} else {
echo '<pre>';
var_dump( wp_remote_retrieve_body( $response ) );
echo '</pre>';
// jsondecode the string received by the API to remove weird backslashes, get and parse the URL and extract the HASH key
$response2 = wp_remote_retrieve_body($response);
parse_str(parse_url(json_decode($response2, true)['url'], PHP_URL_QUERY), $result);
$hash = $result['h'];
//CONVERT JSON array to PHP array
$response3 = json_decode($response2);
$invoicecode = $response3->transport_code; //GET INVOICE CODE from the PHP ARRAY
echo $invoicecode;
$order = wc_get_order( $order_id );
$order->update_meta_data( '_codigo_at', $invoicecode );
$order->save();
}
}
Now I am successfully able to get the code from their response.
However I can't save it because I always get the following PHP fatal error:
PHP Fatal error: Uncaught Error: Call to a member function update_meta_data() on bool in
From what I understood so far, this would likely be because $order is not defined as an object on this filter moloni_after_insert_document
Because when I try just to save a test random meta value but instead using a filter like woocommerce_order_status_completed then $order seems to work for updating meta data, the problem is that I must only run this action after the moloni_after_insert_document filter, because it is only then that the Invoice Code is generated and available
How could I properly define the $order inside of this code?
I am not sure how to handle/proceed in this situation
Thank you in advance for the attention and advice
It is necessary to add
global $woocommerce, $post;
to the code, as adding this global has fixed the problem because it allowed to define the $order object.
I don't know if this is the most efficient way of doing so, but it has managed to make the code work.
I have the following url:
https://blockchain.info/multiaddr?active=1AT4ES3ee1N6iBzzbdK8xvcAV3CBTRKcbS|1FHcYth4LRJMwNx2y8NR5DH7sYCiVzXs3Y&n=1
I want to access the final_balance from the output of the url.
I have the following code:
$value = file_get_contents($url);
$FinalBalance = $value["final_balance"];
var_dump($FinalBalance);
Error PHP Warning: Illegal string offset 'final_balance'
I also tried the following code:
$value = file_get_contents($url);
$json = json_decode($value);
var_dump($json);
$FinalBalance = $json["final_balance"];
var_dump($Final_Balance);
Error PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array
Your are near to finish that stuff but I will write down desired solution. Please have a look.
$url="https://blockchain.info/multiaddr?active=1AT4ES3ee1N6iBzzbdK8xvcAV3CBTRKcbS|1FHcYth4LRJMwNx2y8NR5DH7sYCiVzXs3Y&n=1";
$value = file_get_contents($url);
$FinalBalance = $value;
$data=json_decode($FinalBalance);
echo $data->wallet->final_balance;
echo $data->addresses[0]->final_balance;
echo $data->addresses[1]->final_balance;
exit;
You are going to access the inner object so you have to provide proper reference whether it is an array or an object.
I want to get 28,000 records data from external API.
For this, I use nusoap_client. However, when I test it I don't get any data and I don't get any error.
This is my function:
public function get_all(){
$url = "http://xxx.xx.x.xx:xxx/services/Pending?wsdl";
$client = new \nusoap_client($url, 'wsdl');
$pDate = isset($_GET["Date"]) ? $_GET["Date"] : '26/2/2017 01:01:01';
$operation = 'getPendingData';
$param1 = array(
'Date' => $Date,
);
$result = $client->call($operation, $param1);
print_r($result);
exit();
}
In the API I must get data starting from 26/02/2017 01:01:01. When I test it I don't get any data. When I changed date to 27/02/2017 01:01:01 I got 759 records data.
How to fix this?
I have a Discord servern with 1361 members and on my website I want to display a total number of joined users.
I have figured out how to get all online Members on the server using:
<?php
$jsonIn = file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json');
$JSON = json_decode($jsonIn, true);
$membersCount = count($JSON['members']);
echo "Number of members: " . $membersCount;
?>
What should I do differently to get a total number of ALL users that have joined the server, and not just display the online members?
Now, I realize I am reviving a pretty old thread here, but I figure some might still use an answer. As jrenk pointed out, you should instead access https://discordapp.com/api/guilds/356230556738125824/members.
Your 404: Unauthorized comes from the fact that you are -you guessed it- not authorized.
If you have created a bot, it is fairly easy: just add a request header Authorization: Bot YOUR_BOT_TOKEN_HERE. If you use a normal Discord account, the whole problem is a bit more tricky:
You will first have to send a POST request to https://discordapp.com/api/auth/login and set the body to {"email": "EMAIL_HERE", "password": "PASSWORD_HERE"}.
You will get a response with the parameter token. Save this token, you will need it later. BUT:
NEVER, UNDER ANY CIRCUMSTANCES show anyone this token, as it is equivalent to your login credentials!
With this token, you can now send a POST request to the same address: https://discordapp.com/api/auth/login, but now add the header Authorization: YOUR_BOT_TOKEN_HERE. Note the missing "Bot" at the beginning.
Also, what you mustn't forget:
If you don't add the parameter ?limit=MAX_USERS, you will only get the first guild member. Take a look here to see details.
You have to count the number of online member
here is the working code
<?php
$members = json_decode(file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json'), true)['members'];
$membersCount = 1;
foreach ($members as $member) {
if ($member['status'] == 'online') {
$membersCount++;
}
}
echo "Number of members: " . $membersCount;
?>
You need a bot on your discord server to get all members. Use the Discord js library for example.
First create a discord bot and get a token, see the following url:
https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token
As #2Kreeper noted, do not reveal your token publicly.
Then use the following code, replacing "enter-bot-token-here" and "enter-guild-id-here" with your own information:
<?php
$json_options = [
"http" => [
"method" => "GET",
"header" => "Authorization: Bot enter-bot-token-here"
]
];
$json_context = stream_context_create($json_options);
$json_get = file_get_contents('https://discordapp.com/api/guilds/enter-guild-id-here/members?limit=1000', false, $json_context);
$json_decode = json_decode($json_get, true);
echo '<h2>Member Count</h2>';
echo count($json_decode);
echo '<h2>JSON Output</h2>';
echo '<pre>';
print_r($json_decode);
echo '</pre>';
?>
For anyone still interested, here's the solution I currently use using RestCord:
use RestCord\DiscordClient;
$serverId = <YourGuildId>;
$discord = new DiscordClient([
'token' => '<YourBotToken>'
]);
$limit = 1000;
$membercnt = 0;
$_ids = array();
function getTotalUsersCount($ids, $limit, $serverId, $discord) {
if( count($ids) > 0 ) {
$last_id = max($ids);
$last_id = (int)$last_id;
} else {
$last_id = null;
}
$members = $discord->guild->listGuildMembers(['guild.id' => $serverId, 'limit' => $limit, 'after' => $last_id]);
$_ids = array();
foreach( $members as $member ) {
$ids[] = $member->user->id;
$_ids[] = $member->user->id;
}
if( count($_ids) > 0 ) {
return getTotalUsersCount($ids, $limit, $serverId, $discord);
} else {
return $ids;
}
}
$ids = getTotalUsersCount($_ids, $limit, $serverId, $discord);
$membercnt = count($ids);
echo "Member Count: " . $membercnt;
In addition to Soubhagya Kumar's answer comment by iTeY you can simply use count(), there is no need to loop if you do not require a loop.
I'm reviving this since it still seems to be relevant and the other answers seem a bit too complex I think (maybe the API used to be bad(?)). So:
Generate a permanent discord invite and keep the code at the end (https://discord.gg/xxxxxxx) and then all you do is this:
<?php
$server_code = "xxxxxxx";
$url = "https://discord.com/api/v9/invites/".$server_code."?with_counts=true&with_expiration=true";
$jsonIn = file_get_contents($url);
$json_obj = json_decode($jsonIn, $assoc = false);
$total = $json_obj ->approximate_member_count;
?>
And there you go, that's the total member count. Keep in mind, this will also count the bots I think so you have to account for that if you want to refine it even more
I would like to add a video to a playlist using GData. So I have no problem creating the playlist, but I can't manage to add a video to it.
Here's what I do:
$playlist = $yt->newPlaylistListEntry();
$playlist->summary = $yt->newDescription()->setText("test");
$playlist->title = $yt->newTitle()->setText("test2");
$postLocation = 'http://gdata.youtube.com/feeds/api/users/default/playlists';
$yt->insertEntry($playlist, $postLocation);
$feedUrl = $playlist->getPlaylistVideoFeedUrl();
$videoEntryToAdd = $yt->getVideoEntry(..given id here..);
$newPlaylistListEntry = $yt->newPlaylistListEntry($videoEntryToAdd->getDOM());
$yt->insertEntry($newPlaylistListEntry, $feedUrl);
And I get the following error:
Notice: Trying to get property of non-object in C:...\library\Zend\Gdata\YouTube\PlaylistListEntry.php on line 296
Which is caused by this code:
$feedUrl = $playlist->getPlaylistVideoFeedUrl();
var_dump shows that the $feed_url is NULL. And it shows that $playlist is an object Zend_Gdata_YouTube_PlaylistListEntry, so I can't understand why it writes "property of non-object".
It seems like it is some kind of a bug in the API. So I've made a little workaround. It may seem ugly, but I had no other ideas.
function grab_dump($var)
{
ob_start();
var_dump($var);
return ob_get_clean();
}
function getPlayListLink($playlist) {
$test = grab_dump($playlist);
$test = strstr($test, "http://gdata.youtube.com/feeds/api/playlists/");
return strstr($test, "' countHint='0'", TRUE);
}
function addVideosToPlaylist($videos_arr, $playlistEntry, $yt) {
$feedUrl = getPlayListLink($playlistEntry);
foreach($videos_arr as $video)
{
$videoEntryToAdd = $yt->getVideoEntry($video);
$newPlaylistListEntry = $yt->newPlaylistListEntry($videoEntryToAdd->getDOM());
$yt->insertEntry($newPlaylistListEntry, $feedUrl);
}
}
And simply call it like that:
addVideosToPlaylist($vids_id, $playlist, $yt);