Simple If Else problem, can anyone help?

Hi

Hopefully someone can help me. My knowledge of PHP doesnt go any further than looking at identifying areas of code and copy and paste - as basic as you get!

Basically i have a php script installed that produces an RSS feed for me to use with google base. There is a little problem were it does not pull the sale price(known as special) into googlebase and it will instead show the original price. I have identified what needs to be changed but i dont know the correct syntax.

I somehow need to get something similar to the following IF ELSE into the code below (this is taken from the same php script that shows the special price on the actual rss feed)

foreach ($product_data as $result) {
$special = $model_catalog_product->getProductSpecial($result[‘product_id’]);
if ($special) {
$price = $special;
} else {
$price = $result[‘price’];
}
if ($useTax) {
$price = $currency->format($tax->calculate($price, $result[‘tax_class_id’], $config->get(‘config_tax’)), $currency->getCode());
} else {
$price = $currency->format($price, $currency->getCode());
}

The code below is were i need the If Else inserted.

<?php foreach ($products as $product) { ?>
<item>
<title><?php echo htmlspecialchars($product[‘name’], ENT_QUOTES, ‘utf-8’); ?></title>
<g:brand><?php echo htmlspecialchars($product[‘brand’], ENT_QUOTES, ‘utf-8’); ?></g:brand>
<g:condition>new</g:condition>
<g:product_type><?php echo $taxonomy; ?></g:product_type>
<description><?php echo htmlspecialchars($product[‘desc’], ENT_QUOTES, ‘utf-8’); ?></description>
<link><?php echo str_replace(‘&’, ‘&’, $product[‘href’]); ?></link>
<pubDate><?php echo $product[‘add_date’]; ?></pubDate>
<!–guid isPermaLink=“true”><?php echo $product[‘href’]; ?></guid–>
<g:id><?php echo (int)$product[‘id’]; ?></g:id>
<!–g:upc><?php echo sprintf(“%012s”, $product[‘id’]); ?></g:upc–>
<g:image_link><?php echo $product[‘thumb’]; ?></g:image_link>
<!–g:expiration_date>2010-01-01</g:expiration_date–>
<g:price><?php echo $product[‘price’]; ?></g:price>
<g:mpn><?php echo htmlspecialchars($product[‘model’], ENT_QUOTES, ‘utf-8’); ?></g:mpn>
<g:weight><?php echo $product[‘weight’]; ?></g:weight>
<g:currency><?php echo $config->get(‘config_currency’); ?></g:currency>
</item>
<?php } ?>

The <g:price> is what googlebase reads to get the price of the product. The problem seems to be that there is no if else statement here to output the special price if there is one.

Any help would be greatly appreciated, i tired emailing the developer but i have been ignored and as you can see i’m pretty clueless

<g:price><?php echo $product[‘price’]; ?></g:price>

You should add “if else” to this line of code to match with your demand.

<g:price>
<?php
$special = $model_catalog_product->getProductSpecial($product[‘product_id’]);
if ($special) {
$price = $special;
} else {
$price = $product[‘price’];
}
echo $price;
?>
</g:price>

However I’m not sure that your page already declare the object
“$model_catalog_product” or not?

So if it still not work. Let me know.
I am also the basic programmer. But I hope I can help you from this problem.

Hi

Thanks for your help. When i insert the code i get an error

Notice Undefined index: product_id - in the <g:price> tag

i will attach the full code, this might be of more help to you.


&lt;?php
// Include Config
require_once('config.php');

// ----------CONFIGURATION--------------
$prodLimit	= '200';					// Max Number of products to retrieve
$showModel 	= true; 				//Show Model in product title
$showPrice 	= true; 				//Show Price in product title
$showATC 	= true; 				//Show Add to Cart button
$useTax		= false;				//Show Prices with Tax
$imgWidth 	= '200';				//image width
$imgHeight 	= '200';				//image height
$taxonomy	= 'Electronics &gt; Computers &gt; Laptops';		//see http://www.google.com/basepages/producttype/taxonomy.txt  and browse the product taxonomy for valid XML values.
//---------------------------------------------

// Set Defaults if not set in config
if (!isset($prodLimit) || !$prodLimit) { $prodLimit = '50';}
if (!isset($imgWidth) || !$imgWidth) { $imgWidth = '200';}
if (!isset($imgHeight) || !$imgHeight) { $imgHeight = '200';}

// Install 
if (!defined('DIR_APPLICATION')) {
	exit('opencart not installed');
}

// Startup
require_once(DIR_SYSTEM . 'startup.php');


// Registry
if (file_exists(DIR_SYSTEM . 'library/length.php')) { //v1.4.1+ uses $registry
	$version = '141';
} elseif (!file_exists(DIR_SYSTEM . 'library/currency.php')) { //v132 moved libraries to helper folder instead of library
	$version = '132';
} else {
	$version = '130';
}

if ($version == '141') {

	$registry = new Registry();
	
	// Loader
	$loader = new Loader($registry);
	$registry-&gt;set('load', $loader);
	
	// Config
	$config = new Config();
	$registry-&gt;set('config', $config);

	// Database 
	$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
	$registry-&gt;set('db', $db);

	// Settings
	$query = $db-&gt;query("SELECT * FROM " . DB_PREFIX . "setting");

	foreach ($query-&gt;rows as $setting) {
		$config-&gt;set($setting['key'], $setting['value']);
	}
	
	// Request
	$request = new Request();
	$registry-&gt;set('request', $request);

	// Cache
	$cache = new Cache();
	$registry-&gt;set('cache', $cache);
	
	// Session
	$session = new Session();
	$registry-&gt;set('session', $session);
	
	// Store
	$query = $db-&gt;query("SELECT * FROM " . DB_PREFIX . "store WHERE url = '" . $db-&gt;escape('http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\\\') . '/') . "' OR url = '" . $db-&gt;escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\\\') . '/') . "'");

	foreach ($query-&gt;row as $key =&gt; $value) {
		$config-&gt;set('config_' . $key, $value);
	}

	define('HTTP_SERVER', $config-&gt;get('config_url'));
	define('HTTP_IMAGE', HTTP_SERVER . 'image/');

	if ($config-&gt;get('config_ssl')) {
		define('HTTPS_SERVER', 'https://' . substr($config-&gt;get('config_url'), 7));
		define('HTTPS_IMAGE', HTTPS_SERVER . 'image/');	
	} else {
		define('HTTPS_SERVER', HTTP_SERVER);
		define('HTTPS_IMAGE', HTTP_IMAGE);	
	}
	
	// Language	
	$query = $db-&gt;query("SELECT * FROM ".DB_PREFIX."language WHERE `code` = '" . $config-&gt;get('config_language') . "'");
	$language = new Language($query-&gt;row['directory']);
	$config-&gt;set('config_language_id', $query-&gt;row['language_id']);
	$language-&gt;load($query-&gt;row['filename']);	
	$registry-&gt;set('language', $language);
	
	// Weight
	require_once(DIR_SYSTEM . 'library/weight.php');
	$weight = new Weight($registry);
	$registry-&gt;set('weight', $weight);
	
	// Currency
	require_once(DIR_SYSTEM . 'library/currency.php');
	$currency = new Currency($registry);
	$registry-&gt;set('currency', $currency);
	
	// Tax
	require_once(DIR_SYSTEM . 'library/tax.php');
	$tax = new Tax($registry);
	$registry-&gt;set('tax', $tax);
	
	// Customer
	require_once(DIR_SYSTEM . 'library/customer.php');
	$customer = new Customer($registry);
	$registry-&gt;set('customer', $customer);
	
	// Images
	$loader-&gt;model('tool/image');
	$model_tool_image = $registry-&gt;get('model_tool_image');
	
	// SEO
	$loader-&gt;model('tool/seo_url');
	$model_tool_seo_url = $registry-&gt;get('model_tool_seo_url');
	
	// Product Data
	$loader-&gt;model('catalog/product');
	$model_catalog_product = $registry-&gt;get('model_catalog_product');
	
} else {

	// Loader
	$loader = new Loader();
	Registry::set('load', $loader);

	// Config
	$config = new Config();
	Registry::set('config', $config);

	// Database 
	$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
	Registry::set('db', $db);

	// Settings
	$query = $db-&gt;query("SELECT * FROM " . DB_PREFIX . "setting");

	foreach ($query-&gt;rows as $setting) {
		$config-&gt;set($setting['key'], $setting['value']);
	}

	// Request
	$request = new Request();
	Registry::set('request', $request);

	// Url
	$url = new Url();
	Registry::set('url', $url);

	// Cache
	$cache = new Cache();
	Registry::set('cache', $cache);

	// Language
	if (file_exists(DIR_SYSTEM . 'engine/action.php')) { //v1.3.4 and earlier
		$query = $db-&gt;query("SELECT * FROM ".DB_PREFIX."language WHERE `code` = '" . $config-&gt;get('config_language') . "'");
		$language = new Language($query-&gt;row['directory']);
		$config-&gt;set('config_language_id', $query-&gt;row['language_id']);
		$language-&gt;load($query-&gt;row['filename']);	
		Registry::set('language', $language);
	} else { // 1.4.0
		$language = new Language();
		Registry::set('language', $language);
	}
		
	$loader-&gt;helper('image'); 

	// Weight
	// File location depends on OpenCart version 
	if (file_exists(DIR_SYSTEM . 'library/weight.php')) { //pre-v1.3.2
		require_once(DIR_SYSTEM . 'library/weight.php');
		$weight = new Weight();
	} else { //v1.3.2+
		$loader-&gt;helper('weight');
		$weight = new HelperWeight();
	}
	Registry::set('weight', $weight);

	// Currency
	// File location depends on OpenCart version 
	if (file_exists(DIR_SYSTEM . 'library/currency.php')) { //pre-v1.3.2
		require_once(DIR_SYSTEM . 'library/currency.php');
		$currency = new Currency();
	} else { //v1.3.2+
		$loader-&gt;helper('currency');
		$currency = new HelperCurrency();
	}
	Registry::set('currency', $currency);
	
	// Tax
	// File location depends on OpenCart version 
	if (file_exists(DIR_SYSTEM . 'library/tax.php')) { //pre-v1.3.2
		require_once(DIR_SYSTEM . 'library/tax.php');
		$tax = new Tax();
	} else { //v1.3.2+
		$loader-&gt;helper('tax');
		$tax = new HelperTax();
	}
	Registry::set('tax', $tax);

	// Customer
	// File location depends on OpenCart version 
	if (file_exists(DIR_SYSTEM . 'library/customer.php')) { //pre-v1.3.2
		require_once(DIR_SYSTEM . 'library/customer.php');
		$customer = new Customer();
	} else { //v1.3.2+
		$loader-&gt;helper('customer');
		$customer = new HelperCustomer();
	}
	Registry::set('customer', $customer);
	
	// SEO
	$loader-&gt;model('tool/seo_url');
	$model_tool_seo_url = Registry::get('model_tool_seo_url');
	
	// Product Data
	$loader-&gt;model('catalog/product');
	$model_catalog_product = Registry::get('model_catalog_product');

}

// Base URL
$catalog_url = HTTP_SERVER;
$image_url = HTTP_IMAGE;


// iconv naming fix: http://www.php.net/manual/en/function.iconv.php#47428
//if (!function_exists('iconv') && function_exists('libiconv')) {
//    function iconv($input_encoding, $output_encoding, $string) {
//        return libiconv($input_encoding, $output_encoding, $string);
//    }
//}


$product_data = array();
$product_data = $model_catalog_product-&gt;getLatestProducts($prodLimit);
$products=array();
//foreach ($query-&gt;rows as $result) {
foreach ($product_data as $result) {
	$special = $model_catalog_product-&gt;getProductSpecial($result['product_id']);
	if ($special) { 
		$price = $special; 
	} else {
		$price = $result['price'];
	}
	if ($useTax) {
		$price = $currency-&gt;format($tax-&gt;calculate($price, $result['tax_class_id'], $config-&gt;get('config_tax')), $currency-&gt;getCode());
	} else {
		$price = $currency-&gt;format($price, $currency-&gt;getCode());
	}
	//str_replace('£', '', $price);
	$name  = htmlspecialchars($result['name'], ENT_QUOTES, 'utf-8');
	if ($showModel) {$name .= ' ['.$result['model'] . ']';}
	if ($showPrice) {$name .= ' - '.$price;}
	$name  = html_entity_decode($name, ENT_QUOTES, 'utf-8');
	if ($result['image']) {
		$image = $result['image'];
	} else {
		$image = 'no_image.jpg';
	}
	//$thumb = ($image) ? ((class_exists('HelperImage')) ? HelperImage::resize($image, $imgWidth, $imgHeight) : image_resize($image, $imgWidth, $imgHeight)) : '';
	$thumb = ($image) ? ((class_exists('HelperImage')) ? HelperImage::resize($image, $imgWidth, $imgHeight) : (class_exists('ModelToolImage')) ? $model_tool_image-&gt;resize($image, $imgWidth, $imgHeight) : image_resize($image, $imgWidth, $imgHeight)) : '';
	
	//$description = htmlspecialchars('&lt;img src="' . $thumb . '" /&gt;&lt;br /&gt;', ENT_QUOTES, 'utf-8');
	//$description .= xmlEntities(strip_tags($result['description']));
	//$description .= html_entity_decode_encode_rss($result['description']);
	//$description .= html_entity_decode(html_entity_decode_encode_rss($result['description']));
	//$description .= xmlEntities($result['description']);
	//$badentities = array(
	//	'&scaron;',
	//	'&Scaron;',
	//);
	
	//$description .= xmlEntities(str_replace($badentities, '', $result['description']));
	
	if (!function_exists('iconv')) {
		//$description = iconv("UTF-8","UTF-8//IGNORE",$description);
	} elseif (!function_exists('iconv')) {
		//$description = libiconv("UTF-8","UTF-8//IGNORE",$description);
	}
	
	
	//$description = preg_replace('/[^(\\x20-\\x7F)]*/','', $description);
	
	// reset desc
	//$description = htmlspecialchars('&lt;img src="' . $thumb . '" /&gt;&lt;br /&gt;', ENT_QUOTES, 'utf-8');
	//$description .= $result['description'];
	$description = '&lt;img src="' . $thumb . '" /&gt;&lt;br /&gt;';
	$description .= html_entity_decode($result['description'], ENT_QUOTES, 'utf-8');
	
	$options = $model_catalog_product-&gt;getProductOptions($result['product_id']);
	
	if ($showATC && get_user_browser() == 'firefox') { //Add to cart only works with Firefox.
		$loader-&gt;language('product/product');
		if ($options) {
			//$description .= htmlspecialchars('&lt;form action="index.php?route=product/product&product_id=' . $result['product_id'] . '" method="post"&gt;&lt;input type="submit" value="' . $language-&gt;get('button_add_to_cart') . '" /&gt;&lt;/form&gt;');
			$description .= '&lt;form action="index.php?route=product/product&product_id=' . $result['product_id'] . '" method="post"&gt;&lt;input type="submit" value="' . $language-&gt;get('button_add_to_cart') . '" /&gt;&lt;/form&gt;';
		} else {
			//$description .= htmlspecialchars('&lt;form action="index.php?route=checkout/cart" method="post"&gt;&lt;input type="hidden" name="quantity" value="1" /&gt;&lt;input type="hidden" name="product_id" value="' . $result['product_id'] . '" /&gt;&lt;input type="submit" value="' . $language-&gt;get('button_add_to_cart') . '" /&gt;&lt;/form&gt;');
			$description .= '&lt;form action="index.php?route=checkout/cart" method="post"&gt;&lt;input type="hidden" name="quantity" value="1" /&gt;&lt;input type="hidden" name="product_id" value="' . $result['product_id'] . '" /&gt;&lt;input type="submit" value="' . $language-&gt;get('button_add_to_cart') . '" /&gt;&lt;/form&gt;';
		}
	}
	//$description .= htmlentities(strip_tags($result['description'],'ENT_QUOTES'));
	//$description .= htmlspecialchars($result['description'], ENT_QUOTES, 'utf-8');
	
	$products[]=array(
	'name' =&gt; $name,
	'href' =&gt; $model_tool_seo_url-&gt;rewrite((HTTP_SERVER . 'index.php?route=product/product&product_id=' . $result['product_id'])),
	//'href' =&gt; (HTTP_SERVER . 'index.php?route=product/product&product_id=' . $result['product_id']),
	//'add_date' =&gt; date("D, d M Y H:i:s T", strtotime($result['date_product_added'])),
	'add_date' =&gt; date("D, d M Y H:i:s T", strtotime($result['date_added'])),
	'desc' =&gt; $description,
	'thumb' =&gt; $thumb,
	'id' =&gt; $result['product_id'],
	'price' =&gt; $result['price'],
	'model' =&gt; $result['model'],
	'brand' =&gt; (isset($result['manufacturer'])) ? $result['manufacturer'] : '',
	'weight' =&gt; $weight-&gt;format($result['weight'], $result['weight_class_id']),
	);
}

$entity_custom_from = false;
$entity_custom_to = false;
function html_entity_decode_encode_rss($data) {
	global $entity_custom_from, $entity_custom_to;
	if(!is_array($entity_custom_from) || !is_array($entity_custom_to)){
		$array_position = 0;
		foreach (get_html_translation_table(HTML_ENTITIES) as $key =&gt; $value) {
			//print("&lt;br /&gt;key: $key, value: $value &lt;br /&gt;\
");
			switch ($value) {
				// These ones we can skip
				case '&nbsp;':
					break;
				case '&gt;':
				case '&lt;':
				case '&quot;':
				case '&apos;':
				case '&amp;':
					$entity_custom_from[$array_position] = $key;
					$entity_custom_to[$array_position] = $value;
					$array_position++;
					break;
				default:
					$entity_custom_from[$array_position] = $value;
					$entity_custom_to[$array_position] = $key;
					$array_position++;
			}
		}
	}
	return str_replace($entity_custom_from, $entity_custom_to, $data);
}

header('Content-type: text/xml; charset=utf-8');
echo '&lt;?xml version="1.0" encoding="utf-8"?&gt;';
$store = (($config-&gt;get('config_name')) ? $config-&gt;get('config_name') : $config-&gt;get('config_store'));
?&gt;
&lt;rss version="2.0" xmlns:g="http://base.google.com/ns/1.0"&gt;
&lt;channel&gt;
	&lt;title&gt;&lt;?php echo htmlspecialchars($store, ENT_QUOTES, 'utf-8'); ?&gt;&lt;/title&gt;
	&lt;description&gt;&lt;?php echo htmlspecialchars($store, ENT_QUOTES, 'utf-8'); ?&gt;&lt;/description&gt;
	&lt;link&gt;&lt;?php echo str_replace('&', '&amp;', $catalog_url); ?&gt;&lt;/link&gt;
	&lt;copyright&gt;&lt;?php echo $config-&gt;get('config_store'); ?&gt;&lt;/copyright&gt;
&lt;?php foreach ($products as $product) { ?&gt;
	&lt;item&gt;
        &lt;title&gt;&lt;?php echo htmlspecialchars($product['name'], ENT_QUOTES, 'utf-8'); ?&gt;&lt;/title&gt;
        &lt;g:brand&gt;&lt;?php echo htmlspecialchars($product['brand'], ENT_QUOTES, 'utf-8'); ?&gt;&lt;/g:brand&gt;
		&lt;g:condition&gt;new&lt;/g:condition&gt;
		&lt;g:product_type&gt;&lt;?php echo $taxonomy; ?&gt;&lt;/g:product_type&gt;
        &lt;description&gt;&lt;?php echo htmlspecialchars($product['desc'], ENT_QUOTES, 'utf-8'); ?&gt;&lt;/description&gt;
        &lt;link&gt;&lt;?php echo str_replace('&', '&amp;', $product['href']); ?&gt;&lt;/link&gt;
        &lt;pubDate&gt;&lt;?php echo $product['add_date']; ?&gt;&lt;/pubDate&gt;
        &lt;!--guid isPermaLink="true"&gt;&lt;?php echo $product['href']; ?&gt;&lt;/guid--&gt;
        &lt;g:id&gt;&lt;?php echo (int)$product['id']; ?&gt;&lt;/g:id&gt;
		&lt;!--g:upc&gt;&lt;?php echo sprintf("%012s", $product['id']); ?&gt;&lt;/g:upc--&gt;
        &lt;g:image_link&gt;&lt;?php echo $product['thumb']; ?&gt;&lt;/g:image_link&gt;
		&lt;!--g:expiration_date&gt;2010-01-01&lt;/g:expiration_date--&gt;
		&lt;g:price&gt;&lt;?php echo $product['price']; ?&gt;&lt;/g:price&gt;
		&lt;g:mpn&gt;&lt;?php echo htmlspecialchars($product['model'], ENT_QUOTES, 'utf-8'); ?&gt;&lt;/g:mpn&gt;
		&lt;g:weight&gt;&lt;?php echo $product['weight']; ?&gt;&lt;/g:weight&gt;
		&lt;g:currency&gt;&lt;?php echo $config-&gt;get('config_currency'); ?&gt;&lt;/g:currency&gt;
	&lt;/item&gt;
&lt;?php } ?&gt;
&lt;/channel&gt;
&lt;/rss&gt;

&lt;?php
function get_user_browser() {
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    if(preg_match('/MSIE/i',$u_agent)) {
		return "ie";
	}  elseif(preg_match('/Firefox/i',$u_agent)) {
        return "firefox";
    } elseif(preg_match('/Safari/i',$u_agent)) {
        return "safari";
    } elseif(preg_match('/Chrome/i',$u_agent)) {
        return "chrome";
    } elseif(preg_match('/Flock/i',$u_agent)) {
        return "flock";
    } elseif(preg_match('/Opera/i',$u_agent)) {
        return "opera";
    }
}

function xmlEntities($string) {
    $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);

    foreach ($translationTable as $char =&gt; $entity) {
        $from[] = $entity;
        $to[] = '&#'.ord($char).';';
    }
    return str_replace($from, $to, $string);
}

function remEntities($str) {
  if(substr_count($str, '&') && substr_count($str, ';')) {
    // Find amper
    $amp_pos = strpos($str, '&');
    //Find the ;
    $semi_pos = strpos($str, ';');
    // Only if the ; is after the &
    if($semi_pos &gt; $amp_pos) {
      //is a HTML entity, try to remove
      $tmp = substr($str, 0, $amp_pos);
      $tmp = $tmp. substr($str, $semi_pos + 1, strlen($str));
      $str = $tmp;
      //Has another entity in it?
      if(substr_count($str, '&') && substr_count($str, ';'))
        $str = remEntities($tmp);
    }
  }
  return $str;
}


?&gt;

After I read your source code.
At First forget about my previous comment. :smiley:

Something that you want is already calculate in your code.
So you just put it in the appropriate line.

Line 325 : ‘price’ => $result[‘price’],

Correct it a little bit

Line 325 : ‘price’ => $price,

I think it will work now.
But if it still not correct. Told me again :slight_smile: