I am using the following solution below from another answer. However it will only send files of up to 64MB. How do I send a large file with this method? I could split the file in to pieces but then I can't reconstruct them once they are sent.
$accesskey = "qJXTMmw2Esal8/tXgfWk0RLwMNJ6OQKEt0E8EMZ8VhQrzGi5uqJqeKvi1l7iqnOddp7bdtai5rPpC6ynHttl1w==";$storageAccount = 'mystorage';
$filetoUpload = realpath('./image.jpg');
$containerName = '<yourblobcontainer>';
$blobName = 'image.jpg';
$destinationURL = "https://$storageAccount.blob.core.windows.net/$containerName/$blobName";
function uploadBlob($filetoUpload, $storageAccount, $containerName, $blobName, $destinationURL, $accesskey) {
$currentDate = gmdate("D, d M Y H:i:s T", time());
$handle = fopen($filetoUpload, "r");
$fileLen = filesize($filetoUpload);
$headerResource = "x-ms-blob-cache-control:max-age=3600\nx-ms-blob-type:BlockBlob\nx-ms-date:$currentDate\nx-ms-version:2015-12-11";
$urlResource = "/$storageAccount/$containerName/$blobName";
$arraysign = array();
$arraysign[] = 'PUT'; /*HTTP Verb*/
$arraysign[] = ''; /*Content-Encoding*/
$arraysign[] = ''; /*Content-Language*/
$arraysign[] = $fileLen; /*Content-Length (include value when zero)*/
$arraysign[] = ''; /*Content-MD5*/
$arraysign[] = 'image/png'; /*Content-Type*/
$arraysign[] = ''; /*Date*/
$arraysign[] = ''; /*If-Modified-Since */
$arraysign[] = ''; /*If-Match*/
$arraysign[] = ''; /*If-None-Match*/
$arraysign[] = ''; /*If-Unmodified-Since*/
$arraysign[] = ''; /*Range*/
$arraysign[] = $headerResource; /*CanonicalizedHeaders*/
$arraysign[] = $urlResource; /*CanonicalizedResource*/
$str2sign = implode("\n", $arraysign);
$sig = base64_encode(hash_hmac('sha256', urldecode(utf8_encode($str2sign)), base64_decode($accesskey), true));
$authHeader = "SharedKey $storageAccount:$sig";
$headers = [
'Authorization: ' . $authHeader,
'x-ms-blob-cache-control: max-age=3600',
'x-ms-blob-type: BlockBlob',
'x-ms-date: ' . $currentDate,
'x-ms-version: 2015-12-11',
'Content-Type: image/png',
'Content-Length: ' . $fileLen
];
$ch = curl_init($destinationURL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_INFILE, $handle);
curl_setopt($ch, CURLOPT_INFILESIZE, $fileLen);
curl_setopt($ch, CURLOPT_UPLOAD, true);
$result = curl_exec($ch);
echo ('Result<br/>');
print_r($result);
echo ('Error<br/>');
print_r(curl_error($ch));
curl_close($ch);
}
uploadBlob($filetoUpload, $storageAccount, $containerName, $blobName, $destinationURL, $accesskey);
If you want to upload large size file to Azure Blob Storage with PHP, you can use Azure PHP storage SDK.
For example
<?php
require_once "vendor/autoload.php";
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;
use MicrosoftAzure\Storage\Blob\Models\Block;
use MicrosoftAzure\Storage\Blob\Models\CommitBlobBlocksOptions;
define('CHUNK_SIZE', 1024*1024);//Block Size = 1 MB
try {
$connectionString = "DefaultEndpointsProtocol=https;AccountName=andyprivate;AccountKey=h4pP1fe76m8hdksFW3TvkO6hgw09Mjue7yJOnULPI/g2eU8LGJ+a6k6SrU6dUkOU77waZfU8CacyVMlTWAUA5A==;EndpointSuffix=core.windows.net";
$blobRestProxy = BlobRestProxy::createBlobService($connectionString);
$containerName = "upload";
$blobName = "psd7003.xml";
$fileName="d:/download/psd7003.xml";
$content = fopen("d:/download/psd7003.xml", "rb");
$index = 0;
$continue = True;
$counter = 1;
$blockIds = array();
while (!feof($content))
{
$blockId = str_pad($counter, 6, "0", STR_PAD_LEFT);
$block = new Block();
$block -> setBlockId(base64_encode($blockId));
$block -> setType("Uncommitted");
array_push($blockIds, $block);
echo $blockId . " | " . base64_encode($blockId) . " | " . count($blockIds);
echo " \n ";
echo " -----------------------------------------";
$data=fread($content, CHUNK_SIZE);
echo "Read " . strlen($data) . " of data from file";
echo " \n ";
echo " -----------------------------------------";
echo " \n ";
echo " -----------------------------------------";
echo "Uploading block : " . $blockId + " into blob storage. Please wait.";
echo " -----------------------------------------";
echo " \n ";
$blobRestProxy -> createBlobBlock($containerName, $blobName, base64_encode($blockId), $data);
echo "Uploaded block: " . $blockId . " into blob storage. Please wait";
echo " \n ";
echo " -----------------------------------------";
echo " \n ";
$counter = $counter + 1;
}
fclose($content);
echo "Now committing block list. Please wait.";
echo " -----------------------------------------";
echo " \n ";
echo "hello";
$options = new CommitBlobBlocksOptions();
$option -> setContentType(mime_content_type($fileName));
$blobRestProxy -> commitBlobBlocks($containerName, $blobName, $blockIds,$options);
echo " -----------------------------------------";
echo " \n ";
echo "Blob created successfully.";
}
catch(Exception $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
?>
Besides, if you want to implement it with rest API, please refer to the following steps
1. Read the whole file to bytes, and divide the file into smaller pieces in your code.
Maybe 8 MB for each pieces.
2. Upload each piece with Put Block API.
In each request, it contains a blockid.
3. Make up the blob with Put Block List API.
In this request, you need to put all the blockid in the body in ordered.
Related
function S3_delete($s3_array)
{
$AWSAccessKeyId = 'youraccesskey';
$AWSSecretAccessKey = 'yoursecretaccesskey';
$BucketName = 'yourbucket';
$AWSRegion = 'ap-south-1';
$canonical_uri="/images/coupon_images/medium_banner/2019091810352344157.jpg";
$encoded_uri = str_replace('%2F', '/', rawurlencode($canonical_uri));
if($AWSRegion == 'us-east-1') {
$hostname = trim($BucketName .".s3.amazonaws.com");
$header_string = "host:" . $hostname . "\n";
$signed_headers_string = "host";
} else {
$hostname = trim($BucketName . ".s3-" . $AWSRegion . ".amazonaws.com");
$header_string = "host:" . $hostname . "\n";
$signed_headers_string = "host";
}
$date_text = gmdate('Ymd', time());
$time_text = gmdate('Ymd\THis\Z');
$algorithm = 'AWS4-HMAC-SHA256';
$scope = $date_text . "/" . $AWSRegion . "/s3/aws4_request";
$x_amz_params = array(
'X-Amz-Algorithm' => $algorithm,
'X-Amz-Credential' => $AWSAccessKeyId . '/' . $scope,
'X-Amz-Date' => $time_text,
'X-Amz-SignedHeaders' => $signed_headers_string
);
$expires = 72000;
if ($expires > 0) {
$x_amz_params['X-Amz-Expires'] = $expires;
}
ksort($x_amz_params);
$query_string = "";
foreach ($x_amz_params as $key => $value) {
$query_string .= rawurlencode($key) . '=' . rawurlencode($value) . "&";
}
$query_string = substr($query_string, 0, -1);
$canonical_request = "DELETE\n" . $encoded_uri . "\n" . $query_string . "\n" . $header_string . "\n" . $signed_headers_string . "\nUNSIGNED-PAYLOAD";
$string_to_sign = $algorithm . "\n" . $time_text . "\n" . $scope . "\n" . hash('sha256', $canonical_request, false);
$signing_key = hash_hmac('sha256', 'aws4_request', hash_hmac('sha256', 's3', hash_hmac('sha256', $AWSRegion, hash_hmac('sha256', $date_text, 'AWS4' . $AWSSecretAccessKey, true), true), true), true);
$signature = hash_hmac('sha256', $string_to_sign, $signing_key);
$url = 'https://' . $hostname . $encoded_uri . '?' . $query_string . '&X-Amz-Signature=' . $signature;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
return $httpcode = curl_getinfo($ch);
}
above code give response like this,
SignatureDoesNotMatchThe request signature we calculated does not
match the signature you provided. Check your key and signing
method.AKIAJKLJAHRPH4X4FSMQAWS4-HMAC-SHA256 20190919T053115Z
20190919/ap-south-1/s3/aws4_request
100% work the below code..
S3_delete('201909251745545.jpg','imagesbook/post_blog/'); //call function
function S3_delete($filename,$path)
{
$file_name = $filename;
$file_delete_path = $path;
$aws_access_key_id = 'your-accress-key';
$aws_secret_access_key = 'your-secret-access-key';
$bucket_name = 'your-bucket-name';
$aws_region = 'your-region'; // Enter your aws region Ex. us-east-1
$host_name = $bucket_name . '.s3.amazonaws.com';
$content_acl = 'public-read';
$content_type = '';
$content='';
$content_title = $file_delete_path.$file_name;
$aws_service_name = 's3';
$timestamp = gmdate('Ymd\THis\Z');
$date = gmdate('Ymd');
$request_headers = array();
$request_headers['Content-Type'] = $content_type;
$request_headers['Date'] = $timestamp;
$request_headers['Host'] = $host_name;
$request_headers['x-amz-acl'] = $content_acl;
$request_headers['x-amz-content-sha256'] = hash('sha256',"");
ksort($request_headers);
$canonical_headers = [];
foreach($request_headers as $key => $value)
{
$canonical_headers[] = strtolower($key) . ":" . $value;
}
$canonical_headers = implode("\n", $canonical_headers);
$signed_headers = [];
foreach($request_headers as $key => $value)
{
$signed_headers[] = strtolower($key);
}
$signed_headers = implode(";", $signed_headers);
$canonical_request = [];
$canonical_request[] = "DELETE";
$canonical_request[] = "/" . $content_title;
$canonical_request[] = "";
$canonical_request[] = $canonical_headers;
$canonical_request[] = "";
$canonical_request[] = $signed_headers;
$canonical_request[] = hash('sha256', $content);
$canonical_request = implode("\n", $canonical_request);
$hashed_canonical_request = hash('sha256', $canonical_request);
$scope = [];
$scope[] = $date;
$scope[] = $aws_region;
$scope[] = $aws_service_name;
$scope[] = "aws4_request";
$string_to_sign = [];
$string_to_sign[] = "AWS4-HMAC-SHA256";
$string_to_sign[] = $timestamp;
$string_to_sign[] = implode('/', $scope);
$string_to_sign[] = $hashed_canonical_request;
$string_to_sign = implode("\n", $string_to_sign);
$kSecret = 'AWS4' . $aws_secret_access_key;
$kDate = hash_hmac('sha256', $date, $kSecret, true);
$kRegion = hash_hmac('sha256', $aws_region, $kDate, true);
$kService = hash_hmac('sha256', $aws_service_name, $kRegion, true);
$kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
$signature = hash_hmac('sha256', $string_to_sign, $kSigning);
$authorization = [
'Credential=' . $aws_access_key_id . '/' . implode('/', $scope),
'SignedHeaders=' . $signed_headers,
'Signature=' . $signature
];
$authorization = 'AWS4-HMAC-SHA256' . ' ' . implode( ',', $authorization);
$curl_headers = [ 'Authorization: ' . $authorization ];
foreach($request_headers as $key => $value)
{
$curl_headers[] = $key . ": " . $value;
}
$url = 'https://' . $host_name . '/' . $content_title;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
return curl_exec($ch); // return response data 1
//$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//curl_close($ch);
//return $httpcode;
}
I have a page where I extract "a href" link with a specific "td class". This is my code and my output:
extractlink.php
<?php
include('../simple_html_dom.php');
function getHTML($url,$timeout)
{
$ch = curl_init($url); // initialize curl with given url
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set useragent
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
return #curl_exec($ch);
}
$linkurl = "http://www.betexplorer.com/soccer/czech-republic/1-liga/results/";
$response=getHTML($linkurl);
$html = str_get_html($response);
foreach($html->find("td[class=h-text-center]/a") as $div) {
$show = 'http://www.betexplorer.com' .$div->href . '<br>';
echo $show;
}
?>
extractlink.php output:
Now I'd like to put each link dynamically in my getHTML url into my single.php page. Below you can see code and output:
<?php
include('../simple_html_dom.php');
function getHTML($url,$timeout)
{
$ch = curl_init($url); // initialize curl with given url
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set useragent
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
return #curl_exec($ch);
}
$response=getHTML("http://www.betexplorer.com/soccer/czech-republic/1-liga/brno-slovacko/Sxc6EbMS/",10);
$html = str_get_html($response);
$titles = $html->find("span[class=list-breadcrumb__item__in]"); // 1 per match
$result = $html->find("p[id=js-score]"); // 1
$partial = $html->find("h2[id=js-partial]"); // 1
$best_bets = $html->find("td[class=table-matches__odds colored]/span/span/span"); // 1
$odds = $html->find("td[class=table-matches__odds]"); // 2
function print_odd($odd) {
if (array_key_exists('data-odd', $odd->attr)) {
return $odd->attr['data-odd'];
}
return $odd->children(0)->children(0)->children(0)->attr['data-odd'];
}
$c=0; $b=0; $o=0; $z=0; $h=0; $d=0; $s=0;// two counters
foreach ($titles as $match) {
list($num1, $num2) = explode(':', $result[$c++]->innertext); // <- explode
$num1 = intval($num1);
$num2 = intval($num2);
$num3 = ($num1 + $num2);
$risultato = ($num1 . '-' . $num2);
$risultatounito = ($num1 . '-' . $num2);
list($home, $away) = explode('-', $titles[$z++]->innertext); // <- explode
list($partialht, $partialft) = explode(',', $partial[$o++]->innertext); // <- explode
$partialht = str_replace('(', '', $partialht);
$partialft = str_replace(')', '', $partialft);
$rest = substr($partialht, -1);
$firstCharacter = $partialht[0];
$lastCharacter = $partialht[2];
$firstCharacters = $partialft[1];
$lastCharacters = $partialft[3];
$firstCharacter = intval($firstCharacter);
$lastCharacter = intval($lastCharacter);
$firstCharacters = intval($firstCharacters);
$lastCharacters = intval($lastCharacters);
$somma = $firstCharacter + $lastCharacter;
$sommatwo = $firstCharacters + $lastCharacters;
list($homescoreht, $awayscoreht) = explode(':', $partialht[$d++]->innertext); // <- explode
$homescoreht = intval($homescoreht);
$awayscoreht = intval($awayscoreht);
list($homescoreft, $awayscoreft) = explode(':', $partialft[$s++]->innertext); // <- explode
$homescoreft = intval($homescoreft);
$awayscoreft = intval($awayscoreft);
if ($somma > 0){
$over05ht = "Over 0.5 HT";
}else{
$over05ht = "Under 0.5 HT";
}
if ($num3 > $somma){
$over05sh = "Over 0.5 SH";
}else{
$over05sh = "Under 0.5 SH";
}
$odd1 = print_odd($odds[$b++]);
$odd2 = print_odd($odds[$b++]);
$odd3 = print_odd($odds[$b++]);
$home = strip_tags($home);
$away = strip_tags($away);
$uniquefield = $home . ' ' . $away;
echo "<tr><td class='rtitle'>".
"<td> ".$home.'</td><td> : </td><td>'.$away . " / " . // <- example use
"<td> ".$num1.'</td><td> : </td><td>'.$num2 . " / " . // <- example use
"<td class='first-cell'>".$partialht ."</td> " .
"<td class='first-cell'>".$partialft ."</td> " .
"<td class='first-cell'>".$firstCharacter ."</td> " .
"<td class='first-cell'>".$lastCharacter ."/</td> " .
"<td class='first-cell'>".$firstCharacters ."</td> " .
"<td class='first-cell'>".$lastCharacters ."/</td> " .
"<td class='first-cell'>".$somma ."/</td> " .
"<td class='first-cell'>".$num3 ."/</td> " .
"<td class='first-cell'>".$over05ht ."/</td> " .
"<td class='first-cell'>".$over05sh ."/</td> " .
"<td class='odds'>".$odd1 . ";" .
"".$odd2 . ";" .
"".$odd3 . "</td>" .
"<td class='first-cell'>".$uniquefield ."</td> " .
"</td></tr><br/>";
} //close foreach
?>
single.php output:
So, I'd like to change getHTML url into single.php and inserting each url from extractlink.php
We are trying to generate a CSV file using PHP. But its not generating. We gave 777 permission to the folder and gave hard coded path in header. but its not generating.
Can any body tell me whats i am doing wrong?
if ($ext === 'csv') {
if (($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
$row = 1;
$file = fopen('ids.txt', 'w');
$num_records =count(file($tmpName));
// $calc = 100/$num_records;
$calc=100/ $num_records;
echo "Total ".$num_records." records found.<br/>";
$p = new ProgressBar();
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=pressurecsv.csv");
while ((($data = fgetcsv($handle, 1000, ',')) !== FALSE) && $row != 30) {
// number of fields in the csv
$address = implode(",", $data);
$p->setProgressBarProgress($x);
usleep(1000000*0.1);
$cityclean = str_replace(" ", "+", $address);
$details_url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=false&key=".$api_array[$api_key_status];
// echo $details_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$geoloc = json_decode(curl_exec($ch), true);
// print_r($geoloc);
if ( $geoloc['status'] === "OVER_QUERY_LIMIT" )
{
echo "OVER QUERY LIMIT. Using another key.";
$api_key_status++;
}
//print_r(address_reformat($geoloc['results'][0]));
//convert_to_csv(address_reformat($geoloc['results'][0]), 'report.csv', ',');
$address_tmp=address_reformat($geoloc['results'][0]);
if(isset($geoloc['results'][0]['geometry']['location']['lat']))
// foreach($address_tmp as $product)
{
//print_r($address_tmp);
fputcsv($output, $address_tmp);
}
$lat = $geoloc['results'][0]['geometry']['location']['lat'];
$lng = $geoloc['results'][0]['geometry']['location']['lng'];
// echo $address . "------Latitude: " . $lat . " ---- Longitude: " . $lng;
fwrite($file, $address . "; " . $lat . " ; " . $lng . "\n");
// echo $row." address coordinate fetched.";
$p->getContent();
// echo $address;
echo "<br/>";
// echo $details_url;
$x += $calc;
//$x++;
$row++;
}
$p->setProgressBarProgress(100);
fclose($file);
fclose($handle);
fclose($output) or die("Can't close php://output");
echo "\n To download generated file <a href='ids.txt'>Click Here</a> . \n";
echo " <iframe src='data.php' height='100%' width='100%' frameBorder='0'></iframe>";
}
}
}
I am using PHP CURL to collect some data but if one of the fields in my query is empty it writes the value from the previous loop, how can I correct this so that it enters no data if the value is not set?
<?php
$domains = array( 'http://www.domain.com/' => '1',
'http://www.domain2.com/' => '2'
);
function file_get_contents_curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
foreach ($domains as $url => $urlKey) {
$html = file_get_contents_curl($url);
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description') {
$description = $meta->getAttribute('content');
}
if($meta->getAttribute('name') == 'keywords') {
$keywords = $meta->getAttribute('content');
}
}
echo "Title: " . $title . "<br>";
echo "Description: " . $description . "<br>";
echo "Keywords: " . $keywords . "<br>";
You need to clear the data each time through the loop, as they're retaining their information from the last run through.
foreach ($domains as $url => $urlKey) {
$title = '';
$description = '';
$keywords = '';
...
}
Alternatively you could put the information into an array so you only need to clear one item, something like
foreach ($domains as $url => $urlKey) {
$site_data = array();
...
$site_data['title'] = $nodes->item(0)->nodeValue;
...
echo "Title: " . $site_data['title'] . "<br>";
echo "Description: " . $site_data['description'] . "<br>";
echo "Keywords: " . $site_data['keywords'] . "<br>";
}
I have inherited a project from a client that uses JSON and PHP to display real estate property listings from a online realty service. The data provided by the service loads, but the properties and agents associated with them get mixed up. Sometimes all of the properties are displayed, but have only one agent associated with them. Other times the data loads, but does not transition after a few properties have been displayed. The transitions are being controlled by the jQuery cycle plugin.
I have included all of the code below. Any assistance is greatly appreciated.
Thank you.
Mike
<?php
function decode_json_string($json){
$objects = array();
$start_pos = strpos($json, '[');
$end_pos = strpos($json, ']');
$dataString = substr($json, ++$start_pos, ($end_pos - $start_pos));
while(strpos($dataString, '{') !== FALSE){
$start_pos = strpos($dataString, '{');
$end_pos = strpos($dataString, '}');
$objectString = substr($dataString, ++$start_pos, ($end_pos - $start_pos));
$tempString = $objectString;
$formattedString = "";
while(strpos($tempString, ':') !== FALSE){
$valueStart = strpos($tempString, ':');
if($tempString[++$valueStart] != '"'){
$substring1 = substr($tempString, 0, $valueStart);
if(strpos($tempString, ',', $valueStart) !== FALSE){
$valueEnd = strpos($tempString, ',', $valueStart);
$substring2 = substr($tempString, $valueStart, ($valueEnd - $valueStart));
}
else{
$valueEnd = $valueStart + 1;
$substring2 = substr($tempString, $valueStart);
}
$formattedString .= $substring1 . '"' . $substring2 . '"';
$tempString = substr($tempString, $valueEnd);
}
else{
$valueEnd = strpos($tempString, '",') + 1;
$formattedString .= substr($tempString, 0, $valueEnd);
$tempString = substr($tempString, $valueEnd);
}
}
$tempArray = explode('",', $formattedString);
foreach($tempArray as $tempValue){
$tempValueArray = explode( ":", $tempValue);
$key = format_string($tempValueArray[0]);
$value = format_string($tempValueArray[1]);
$object[$key] = $value;
}
$objects[] = $object;
$dataString = substr($dataString, ++$end_pos);
}
return $objects;
}
function format_string($string){
$string = str_replace("'", "", $string);
$string = str_replace('"', "", $string);
return trim($string);
}
function get_agent_properties_json($agentID){
global $BASE_URL;
$date = time();
$dataType = '3'; // Data Type = Properties
$url = $BASE_URL . '/FeaturedDataHandler.c?r=' . $date . '&DataType=' . $dataType . '&CompanyID=' . $companyID . '&agentID=' . $agentID;
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$response = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
return $response;
}
function get_agent_properties($agentID){
$agent_properties_json = get_agent_properties_json($agentID);
$properties = decode_json_string($agent_properties_json);
return $properties;
}
function print_property_details(&$property, &$agent){
global $BASE_URL;
if($property['ListingStatusCode'] != 'SOLD'){
$address = $property['Address'];
$shortaddr = substr($address, 0, -12);
echo "<div class='propertySlide'>";
echo "<div class='title'>";
echo "<div class='box1'>";
echo "<span class='price'>". $property['Price'] ."</span>";
echo "<span class='address'>". $shortaddr ."</span>";
echo "</div>";
echo "<div class='box2'>";
echo "<span class='style'><strong>Style:</strong> ". $property['Style'] ."</span>";
echo "<span class='footage'><strong>Sq. Feet:</strong> ". $property['SqFootage'] ."</span>";
echo "<span class='beds'><strong>Beds:</strong> ". $property['Bedrooms'] ."</span>";
echo "<span class='baths'><strong>Baths:</strong> ". $property['Bathrooms'] ."</span>";
echo "<span class='year'><strong>Year Built:</strong> ". $property['YearBuilt'] ."</span>";
echo "</div>";
echo "</div>";
echo "<div class='imagebox'><img class='listingImage' src='". $BASE_URL . $property['Image'] ."' /></div>";
echo "<div class='agentbox'>";
echo "<img class='agentImage' src='" . $BASE_URL . "/Users/pic" . $agent['WTLUserID'] . ".jpg' />";
echo "<span class='agent'><strong>Agent:</strong> ". $agent['DisplayName'] ."</span>";
echo "</div>";
echo "</div>";
}
}
?>
$date = time();
$dataType = '4'; // Data Type = Agents
$companyID = '2119'; // Red Deer - Century 21 Advantage
$url = $BASE_URL . '/FeaturedDataHandler.c?r=' . $date . '&DataType=' . $dataType . '&CompanyID=' . $companyID;
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$response = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
$agents = decode_json_string($response);
foreach($agents as $agent){
$properties = get_agent_properties($agent['WTLUserID']);
foreach($properties as $property){
print_property_details($property, $agent);
}
}
<?php
$BASE_URL = 'http://www.century21.ca';
$date = time();
$dataType = '4'; // Data Type = Agents
$companyID = '2119'; // Red Deer - Century 21 Advantage
$url = $BASE_URL . '/FeaturedDataHandler.c?r=' . $date . '&DataType=' . $dataType . '&CompanyID=' . $companyID;
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$response = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
$agents = decode_json_string($response);
foreach($agents as $agent){
$properties = get_agent_properties($agent['WTLUserID']);
foreach($properties as $property){
print_property_details($property, $agent);
}
}
Before trying to debug the decode_json_string() function here you should try PHP's built-in json_decode() http://php.net/manual/en/function.json-decode.php
If you have an older version of PHP that lacks json_decode() you can find a compatible one in upgrade.php