| Server IP : 80.211.21.168 / Your IP : 216.73.217.33 Web Server : Apache System : Linux alex-webdesign.it 3.10.0-1160.119.1.el7.tuxcare.els22.x86_64 #1 SMP Mon Aug 18 06:07:12 UTC 2025 x86_64 User : admin_japan ( 10003) PHP Version : 8.2.32 Disable Function : opcache_get_status MySQL : OFF | cURL : ON | WGET : OFF | Perl : OFF | Python : OFF | Sudo : OFF | Pkexec : OFF Directory : /var/www/vhosts/cerchijapan.it/ai4dealers.com/ |
Upload File : |
<?php
/**
* Scarica l'HTML di una pagina via cURL.
*
* @param string $url
* @return string
* @throws Exception se il download fallisce
*/
function fetchHtml(string $url): string
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => 'Mozilla/5.0',
]);
$html = curl_exec($ch);
if ($html === false) {
throw new Exception('Errore cURL: ' . curl_error($ch));
}
curl_close($ch);
return $html;
}
/**
* Estrae il codice veicolo dal JSON __NEXT_DATA__ presente nell'HTML.
*
* @param string $html
* @return string Il codice che compare in "[Veicolo: CODE]"
* @throws Exception se qualcosa va storto
*/
function extractVehicleCode(string $html): string
{
// 1) Trovo il JSON __NEXT_DATA__
if (!preg_match(
'#<script[^>]*id=(?:\'|")__NEXT_DATA__(?:\'|")[^>]*>(.*?)</script>#si',
$html,
$m
)) {
throw new Exception('Script __NEXT_DATA__ non trovato');
}
$jsonText = $m[1];
// 2) Decodifico il JSON
$data = json_decode($jsonText, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('JSON malformato: ' . json_last_error_msg());
}
// 3) Estraggo ESATTAMENTE listingDetails → description
if (
!isset($data['props']) ||
!isset($data['props']['pageProps']) ||
!isset($data['props']['pageProps']['listingDetails']) ||
!isset($data['props']['pageProps']['listingDetails']['description'])
) {
throw new Exception('Campo description non trovato nel JSON');
}
$rawDesc = $data['props']['pageProps']['listingDetails']['description'];
// 4) Decodifico eventuali entità HTML/Unicode
$description = html_entity_decode($rawDesc, ENT_QUOTES | ENT_HTML5);
// 5) Estraggo il codice dentro "[Veicolo: ...]"
if (!preg_match('/\[Veicolo:\s*([^\]]+)\]/u', $description, $m2)) {
throw new Exception('Codice veicolo non trovato in description');
}
return trim($m2[1]);
}
/**
* Wrapper: dato un URL, restituisce il codice veicolo.
*
* @param string $url
* @return string
*/
function getVehicleCode(string $url): string
{
$html = fetchHtml($url);
return extractVehicleCode($html);
}
// ——— Esempio di utilizzo ———
try {
$url = 'https://www.autoscout24.it/annunci/volkswagen-polo-1-0-evo-80cv-benzina-bianco-bcfc6d32-09b9-4dbc-bb00-457a38deeb0b?source=dealerpage_stock-list';
$code = getVehicleCode($url);
echo "{$code}\n"; // es. "U26080"
} catch (Exception $e) {
echo 'Errore: ' . $e->getMessage() . "\n";
}