Shagshag
6/10/2015 - 3:00 PM

addons_rate.php

<?php
header('Content-Type: application/json');

$id_product = (int)$_GET['id_product'];
if (!$id_product)
{
	$result = array(
		'status' => 'fail',
		'data' => array(
			'id_product' => 'id_product is required'
		)
	);
}
else
{
	$url = 'http://addons.prestashop.com/product.php?id_product=';
	$html = fetchUrl($url.$id_product);
	if ($html)
	{
		$matches = array();
		preg_match('|<meta itemprop="rating" content="(\d+)"|', $html, $matches);
		$rating = empty($matches)?false:(float)$matches[1];
		preg_match('|<meta itemprop="count" content="(\d+)"|', $html, $matches);
		$count = empty($matches)?false:(float)$matches[1];

		$result = array(
			'status' => 'success',
			'data' => array(
				'id_product' => $id_product,
				'rating' => $rating,
				'rating_count' => $count
			)
		);
	}
	else
	{
		$result = array(
			'status' => 'fail',
			'data' => array(
				'id_product' => 'product not found'
			)
		);
	}
}
echo json_encode($result);

function fetchUrl($uri)
{
	$handle = curl_init();

	curl_setopt($handle, CURLOPT_URL, $uri);
	curl_setopt($handle, CURLOPT_POST, false);
	curl_setopt($handle, CURLOPT_BINARYTRANSFER, false);
	curl_setopt($handle, CURLOPT_HEADER, true);
	curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 10);
	curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 1);

	$response = curl_exec($handle);
	$hlength  = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
	$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
	$body     = substr($response, $hlength);
	$url      = curl_getinfo($handle, CURLINFO_EFFECTIVE_URL);

	// If HTTP response is not 200, throw exception
	if ($httpCode != 200)
		return false;
	if (substr($url, -5) != '.html')
		return false;

	return $body;
}