Simple HTML Dom change link source dinamically - php

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

Related

PHP Azure blob upload larger than allowed size

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.

php cURL doesnt print out anything

I am trying to send a HTML form POST data with a cURL, but it seems the response is always empty. I first save all the POST data in an array, and use an implode function. When I echo out the implode string it does return the values, but after the cURL it's just empty.
This is the setup. I call this function after submitting the form
$this->OCIcURL($this->request->post);
public function OCIcURL($post) {
$data_oci = array();
$items_oci = array();
$counter = 0;
$data_oci['~caller'] = 'CTLG';
foreach ($post['item'] as $key => $value)
{
$counter++;
$data_oci['NEW_ITEM-DESCRIPTION[' . $counter . ']'] = $value;
$data_oci['NEW_ITEM-MATNR[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-QUANTITY[' . $counter . ']'] = $post['amount'][$counter];
$data_oci['NEW_ITEM-UNIT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-PRICE[' . $counter . ']'] = $post['price'][$counter];
$data_oci['NEW_ITEM-CURRENCY[' . $counter . ']'] = $this->session->data['currency'];
$data_oci['NEW_ITEM-PRICEUNIT[' . $counter . ']'] = 1;
$data_oci['NEW_ITEM-LEADTIME[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-VENDOR[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-VENDORMAT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-MANUFACTCODE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-MANUFACTMAT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-MATGROUP[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-SERVICE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-CONTRACT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-CONTRACT_ITEM[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_QUOTE_ID[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_QUOTE_ITEM[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_PRODUCT_ID[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-ATTACHMENT[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-ATTACHMENT_TITLE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-ATTACHMENT_PURPOSE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_SCHEMA_TYPE[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-EXT_CATEGORY_ID[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-CUST_FIELD1[' . $counter . ']'] = 21;
$data_oci['NEW_ITEM-PARENT_ID[' . $counter . ']'] = "";
$data_oci['NEW_ITEM-ITEM_TYPE[' . $counter . ']'] = "";
}
foreach ($data_oci as $key => $value)
{
$items_oci[] = $key . '=' . $value;
}
$string_oci = implode('&', $items_oci);
If I echo out the $string_oci I do get a result. After this I use the cURL to send the string to a link.
$url = "http://localhost/test.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string_oci);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
var_dump($response);
}
The var_dump is always empty, returning string(0) "". I also tried this on the live website, same result.
I used this piece of code to see any errors, but it seems it there arent any error at all, but the var_dump is always empty.
if (curl_exec($ch) === FALSE)
{
print_r(curl_getinfo($ch));
die("Curl error: " . curl_error($ch));
}
else
{
curl_close($ch);
}
$endpoint="http://localhost/test3.php";
$session = curl_init($endpoint);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($session, CURLOPT_POSTFIELDS, $string_oci);
curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($session);
var_dump($response);
curl_close($session);
You need a header in your curl request and your curl_init needs a url. Try the code i attach.

Curl for loop writes previous loops value if there is no data in the current loop

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>";
}

PHP Call Function from Inside Itself Until Condition Met

I have a function that I am creating that basically connects to the Google Plus API and Pulls information. Unfortunately in order to get more than a few results at a time you need to use the nextPageToken provided in the API callback. Here is what I have so far:
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function parseResults($nextPageToken = "") {
$count = 0;
$content = get_data('https://www.googleapis.com/plus/v1/activities?query=%23throughglass&maxResults=10&orderBy=recent&fields=items(actor(displayName%2Curl)%2Cid%2Cobject(actor%2Cattachments)%2Curl%2Cverb)%2CnextPageToken&pageToken=' . $nextPageToken . '&key=YOUR API KEY HERE');
$posts = json_decode($content);
$token = $posts->nextPageToken;
foreach ($posts->items as $value){
$id = $value->id;
$id_query = mysql_query("SELECT id FROM images WHERE id = '$id'");
if ($value->verb != "post") continue;
if (mysql_num_rows($id_query) > 0) continue;
echo $value->actor->displayName . "<br />";
$count++;
}
if ($count < 20){
parseResults($token);
}else{
break;
}
}
parseResults();
If you can kind of see what I am trying to do here hopefully someone can help me out. I basically want to keep re-calling the parseResults() function with the provided nextPageToken until there have been 20 records processed.
I was able to solve it with help from Lawrence above:
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function parseResults($nextPageToken = "", $count) {
$content = get_data('https://www.googleapis.com/plus/v1/activities?query=%23throughglass&maxResults=10&orderBy=recent&fields=items(actor(displayName%2Curl)%2Cid%2Cobject(actor%2Cattachments)%2Curl%2Cverb)%2CnextPageToken&pageToken=' . $nextPageToken . '&key={YOUR_API_KEY}');
$posts = json_decode($content);
$token = $posts->nextPageToken;
foreach ($posts->items as $value){
$id = $value->id;
$name = $value->actor->displayName;
$profile = $value->actor->url;
$post = $value->url;
$post_text = $value->object->attachments[0]->displayName;
$image_small = $value->object->attachments[0]->image->url;
$image_full = $value->object->attachments[0]->fullImage->url;
$id_query = mysql_query("SELECT id FROM images WHERE id = '$id'");
if (mysql_num_rows($id_query) > 0) continue;
if ($value->verb != "post") continue;
if ($value->object->attachments[0]->image->url == "" || $value->object->attachments[0]->fullImage->url == "") continue;
if ($post_text != "#throughglass") continue;
mysql_query("INSERT INTO images (id,
author_name,
author_url,
post_url,
post_text,
image_small,
image_full) VALUES (
'$id',
'$name',
'$profile',
'$post',
'$post_text',
'$image_small',
'$image_full')");
echo "<b>ID: </b>" . $id . "<br />";
echo "<b>Name: </b>" . $value->actor->displayName . "<br />";
echo "<b>Profile URL: </b>" . $value->actor->url . "<br />";
echo "<b>Post URL: </b>" . $value->url . "<br />";
echo "<b>Post Text: </b>" . $value->object->attachments[0]->displayName . "<br />";
echo "<b>Image Small: </b>" . $value->object->attachments[0]->image->url . "<br />";
echo "<b>Image Full: </b>" . $value->object->attachments[0]->fullImage->url . "<br /><br />";
$count++;
}
if ($count < 100){
parseResults($token, $count);
}else{
echo "<br /><br /><br />" . $token;
break;
}
}
parseResults("", 0);
I think you want to count the number of recursive calls.
You can achive this by wrapping the function into a class an use a class property, but an easiest wayt would be to add a parameter to your function parseResult and increment it before the next call.

JSON and PHP driven slideshow not working

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

Categories