Pregunta
¿Cómo puedo obtener varias páginas de resultados automáticamente?
Respuesta
A veces, puede ser conveniente obtener varias páginas de resultados de usuario y volcarlas en un archivo JSON. Para hacer esto, creé un script en PHP, está adjunto y también pegado a continuación.
<?php
$resource = ''; // put the name of the endpoint here, for example organizations, tickets
$start_page = 1; // first page you want to load
$end_page = 10; // last page you want to load (it could take a while if too big)
$subdomain = ''; // your zendesk subdomain
$userpwd = ''; // your zendesk username and password, or username/token and api token. - {username}/token:{token} or {username}:{password}
function makerequest($url, $userpwd) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $userpwd);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
$result = curl_exec($ch);
if (curl_errno($ch)) $result = curl_error($ch);
curl_close($ch);
return $result;
}
function getpages($resource, $start_page, $end_page, $userpwd, $subdomain){
$url = isset($url) ? $url : "https://$subdomain.zendesk.com/api/v2/$resource.json";
$i = $start_page;
$array = Array();
while (1) {
if ($i > $end_page) {
$file = fopen("results.json", "w") or exit("Unable to open file!");
fwrite($file, json_encode(array($resource => $array)));
fclose($file);
break;
}
$results = json_decode(makerequest($url, $userpwd));
$array = array_merge($array, $results->$resource);
$url = $results->next_page;
$i++;
}
}
getpages($resource, $start_page, $end_page, $userpwd, $subdomain);
?>
Descargue este script o cópielo y péguelo en un archivo llamado paginate.php. Complete las variables del inicio, $resource, $start_page, $end_page, $subdomain y $userpwd, como se explica en los comentarios del script.
Luego, vaya a la carpeta donde descargó el archivo y desde el terminal ejecute el comando php paginate.php para crear el nuevo archivo con los resultados, en un archivo llamado results.json. El archivo está diseñado para sobrescribir y no para anexar.
Después de recibir los resultados, puede procesarlos según sea necesario. Esta información puede ser útil para encontrar qué entradas en la matriz eran únicas y cuáles duplicadas. Para ello, muestre los resultados en el archivo results.json y luego ejecute uno de los dos comandos siguientes: el primero muestra la cantidad de resultados únicos y el segundo muestra los valores únicos reales:
cat results.json | jq '.' | grep '"id"' > sort > uniq -c > uniq.txt
cat results.json | jq '.' | grep '"id"' > sort > uniq > uniq.txt
Para usar estos comandos también es necesario tener jq, que se puede descargar de: https://stedolan.github.io/jq/download/.
Además, esta información puede ser útil para exportar los datos para importarlos a un sistema nuevo.
Descargo de responsabilidad de la traducción: Este artículo ha sido traducido usando software de traducción automática para proporcionar una idea básica del contenido. Se han realizado esfuerzos razonables para proporcionar una traducción exacta, sin embargo, Zendesk no garantiza la exactitud de la traducción.
Si surge alguna pregunta relacionada con la exactitud de la información incluida en el artículo traducido, consulte la versión en inglés del artículo, que es la versión oficial.
2 comentarios
Brett Bowser
Thanks for taking the time to share this with everyone Seneca :)
0
Seneca Spurling
It seems that CURLOPT_SSL_VERIFYHOST now needs to be set to 2.
If you don't already have php-curl installed, you'll need that package as well.
If you run it and get a zero-length output file, try changing the $end_page to 2. If you ask for a page that doesn't exist it overwrites the file with nothing at all. However it seems to handle things correctly up to then. You get 100 records per page, so for example if you have 650 records, you'll need to set $end_page to 6.
If you're getting organizations, for example, you can use something like this to get the count so you know how many pages to get. The count may not be accurate over 100,000. See https://developer.zendesk.com/rest_api/docs/support/organizations.
I know this is just an example and not meant to be robust. This isn't a complaint or request for changes, just adding these comments here in case they help someone like myself in the future.
0
Iniciar sesión para dejar un comentario.