belial9826

Code PHP Apify

Sep 13th, 2024
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.27 KB | Source Code | 0 0
  1. function get_facebook_reactions() {
  2.     // Asignar la URL del post de Facebook, API key de Apify y el ID del actor a variables
  3.     $facebook_post_url = 'https://www.facebook.com/julian9826G/posts/pfbid0tQCukmnsuJmkXShgJfNpjrKwcdJ8ymE1AkcLLhPWNfJzArgMZZx7c6RNP9Cg8YhDl';
  4.     $apify_api_key = 'apify_api_VudNw3Y940vAhBlw5GptSCGqGLtdsL34gHug';
  5.     $apify_actor_id = 'XKQI0Jr9lTVSx0BiH';
  6.  
  7.     // API URL para ejecutar el actor en Apify
  8.     $apify_url = "https://api.apify.com/v2/acts/$apify_actor_id/runs";
  9.  
  10.     // Crear el cuerpo de la solicitud
  11.     $body = json_encode(array(
  12.         'startUrls' => array(
  13.             array('url' => $facebook_post_url)
  14.         )
  15.     ));
  16.  
  17.     echo "<pre>";
  18.     print_r($body);
  19.     echo "</pre><br><br><br>";
  20.  
  21.     // Hacer la solicitud a la API de Apify
  22.     $response = wp_remote_post($apify_url, array(
  23.         'body'    => $body,
  24.         'timeout' => 60, // Tiempo de espera
  25.         'headers' => array(
  26.             'Authorization' => 'Bearer ' . $apify_api_key,
  27.             'Content-Type'  => 'application/json',
  28.         ),
  29.     ));
  30.  
  31.     // Verificar si la respuesta contiene errores
  32.     if (is_wp_error($response)) {
  33.         // Print the error in case the request fails
  34.         echo 'Error contacting Apify: ' . $response->get_error_message().'<br><br><br>';
  35.         return;
  36.     }
  37.  
  38.     // Obtener el cuerpo de la respuesta
  39.     $response_body = wp_remote_retrieve_body($response);
  40.  
  41.  
  42.     // Check if the response body is not empty
  43.     if (!empty($response_body)) {
  44.         // Decode the JSON response
  45.         $likes_data = json_decode($response_body, true);
  46.  
  47.         // Display the full result to inspect the structure
  48.         echo 'Full result from Apify: <br>';
  49.         echo "<pre>";
  50.         print_r($likes_data);
  51.         echo "</pre><br><br><br>";
  52.  
  53.         // If the likes/reactions data exists, print it
  54.         if (isset($likes_data[0]['likes'])) {
  55.             $total_likes = intval($likes_data[0]['likes']);
  56.             echo '<br><br><br>Total reactions/likes: ' . $total_likes;
  57.         } else {
  58.             echo '<br><br><br>No likes/reactions were found in the response.';
  59.         }
  60.     } else {
  61.         // If no valid response was received, print a message
  62.         echo 'No valid response received from Apify.';
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment