SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Nov 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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('&', '&amp;', $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

  2. #2
    SitePoint Member
    Join Date
    Nov 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    <grice><?php echo $product['price']; ?></grice>

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

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

    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.

  3. #3
    SitePoint Member
    Join Date
    Nov 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

    Code:
    <?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 > Computers > 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->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->query("SELECT * FROM " . DB_PREFIX . "setting");
    
    	foreach ($query->rows as $setting) {
    		$config->set($setting['key'], $setting['value']);
    	}
    	
    	// Request
    	$request = new Request();
    	$registry->set('request', $request);
    
    	// Cache
    	$cache = new Cache();
    	$registry->set('cache', $cache);
    	
    	// Session
    	$session = new Session();
    	$registry->set('session', $session);
    	
    	// Store
    	$query = $db->query("SELECT * FROM " . DB_PREFIX . "store WHERE url = '" . $db->escape('http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "' OR url = '" . $db->escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
    
    	foreach ($query->row as $key => $value) {
    		$config->set('config_' . $key, $value);
    	}
    
    	define('HTTP_SERVER', $config->get('config_url'));
    	define('HTTP_IMAGE', HTTP_SERVER . 'image/');
    
    	if ($config->get('config_ssl')) {
    		define('HTTPS_SERVER', 'https://' . substr($config->get('config_url'), 7));
    		define('HTTPS_IMAGE', HTTPS_SERVER . 'image/');	
    	} else {
    		define('HTTPS_SERVER', HTTP_SERVER);
    		define('HTTPS_IMAGE', HTTP_IMAGE);	
    	}
    	
    	// Language	
    	$query = $db->query("SELECT * FROM ".DB_PREFIX."language WHERE `code` = '" . $config->get('config_language') . "'");
    	$language = new Language($query->row['directory']);
    	$config->set('config_language_id', $query->row['language_id']);
    	$language->load($query->row['filename']);	
    	$registry->set('language', $language);
    	
    	// Weight
    	require_once(DIR_SYSTEM . 'library/weight.php');
    	$weight = new Weight($registry);
    	$registry->set('weight', $weight);
    	
    	// Currency
    	require_once(DIR_SYSTEM . 'library/currency.php');
    	$currency = new Currency($registry);
    	$registry->set('currency', $currency);
    	
    	// Tax
    	require_once(DIR_SYSTEM . 'library/tax.php');
    	$tax = new Tax($registry);
    	$registry->set('tax', $tax);
    	
    	// Customer
    	require_once(DIR_SYSTEM . 'library/customer.php');
    	$customer = new Customer($registry);
    	$registry->set('customer', $customer);
    	
    	// Images
    	$loader->model('tool/image');
    	$model_tool_image = $registry->get('model_tool_image');
    	
    	// SEO
    	$loader->model('tool/seo_url');
    	$model_tool_seo_url = $registry->get('model_tool_seo_url');
    	
    	// Product Data
    	$loader->model('catalog/product');
    	$model_catalog_product = $registry->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->query("SELECT * FROM " . DB_PREFIX . "setting");
    
    	foreach ($query->rows as $setting) {
    		$config->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->query("SELECT * FROM ".DB_PREFIX."language WHERE `code` = '" . $config->get('config_language') . "'");
    		$language = new Language($query->row['directory']);
    		$config->set('config_language_id', $query->row['language_id']);
    		$language->load($query->row['filename']);	
    		Registry::set('language', $language);
    	} else { // 1.4.0
    		$language = new Language();
    		Registry::set('language', $language);
    	}
    		
    	$loader->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->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->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->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->helper('customer');
    		$customer = new HelperCustomer();
    	}
    	Registry::set('customer', $customer);
    	
    	// SEO
    	$loader->model('tool/seo_url');
    	$model_tool_seo_url = Registry::get('model_tool_seo_url');
    	
    	// Product Data
    	$loader->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->getLatestProducts($prodLimit);
    $products=array();
    //foreach ($query->rows as $result) {
    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());
    	}
    	//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->resize($image, $imgWidth, $imgHeight) : image_resize($image, $imgWidth, $imgHeight)) : '';
    	
    	//$description = htmlspecialchars('<img src="' . $thumb . '" /><br />', 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('<img src="' . $thumb . '" /><br />', ENT_QUOTES, 'utf-8');
    	//$description .= $result['description'];
    	$description = '<img src="' . $thumb . '" /><br />';
    	$description .= html_entity_decode($result['description'], ENT_QUOTES, 'utf-8');
    	
    	$options = $model_catalog_product->getProductOptions($result['product_id']);
    	
    	if ($showATC && get_user_browser() == 'firefox') { //Add to cart only works with Firefox.
    		$loader->language('product/product');
    		if ($options) {
    			//$description .= htmlspecialchars('<form action="index.php?route=product/product&product_id=' . $result['product_id'] . '" method="post"><input type="submit" value="' . $language->get('button_add_to_cart') . '" /></form>');
    			$description .= '<form action="index.php?route=product/product&product_id=' . $result['product_id'] . '" method="post"><input type="submit" value="' . $language->get('button_add_to_cart') . '" /></form>';
    		} else {
    			//$description .= htmlspecialchars('<form action="index.php?route=checkout/cart" method="post"><input type="hidden" name="quantity" value="1" /><input type="hidden" name="product_id" value="' . $result['product_id'] . '" /><input type="submit" value="' . $language->get('button_add_to_cart') . '" /></form>');
    			$description .= '<form action="index.php?route=checkout/cart" method="post"><input type="hidden" name="quantity" value="1" /><input type="hidden" name="product_id" value="' . $result['product_id'] . '" /><input type="submit" value="' . $language->get('button_add_to_cart') . '" /></form>';
    		}
    	}
    	//$description .= htmlentities(strip_tags($result['description'],'ENT_QUOTES'));
    	//$description .= htmlspecialchars($result['description'], ENT_QUOTES, 'utf-8');
    	
    	$products[]=array(
    	'name' => $name,
    	'href' => $model_tool_seo_url->rewrite((HTTP_SERVER . 'index.php?route=product/product&product_id=' . $result['product_id'])),
    	//'href' => (HTTP_SERVER . 'index.php?route=product/product&product_id=' . $result['product_id']),
    	//'add_date' => date("D, d M Y H:i:s T", strtotime($result['date_product_added'])),
    	'add_date' => date("D, d M Y H:i:s T", strtotime($result['date_added'])),
    	'desc' => $description,
    	'thumb' => $thumb,
    	'id' => $result['product_id'],
    	'price' => $result['price'],
    	'model' => $result['model'],
    	'brand' => (isset($result['manufacturer'])) ? $result['manufacturer'] : '',
    	'weight' => $weight->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 => $value) {
    			//print("<br />key: $key, value: $value <br />\n");
    			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 '<?xml version="1.0" encoding="utf-8"?>';
    $store = (($config->get('config_name')) ? $config->get('config_name') : $config->get('config_store'));
    ?>
    <rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">
    <channel>
    	<title><?php echo htmlspecialchars($store, ENT_QUOTES, 'utf-8'); ?></title>
    	<description><?php echo htmlspecialchars($store, ENT_QUOTES, 'utf-8'); ?></description>
    	<link><?php echo str_replace('&', '&amp;', $catalog_url); ?></link>
    	<copyright><?php echo $config->get('config_store'); ?></copyright>
    <?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('&', '&amp;', $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 } ?>
    </channel>
    </rss>
    
    <?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 => $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 > $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;
    }
    
    
    ?>

  4. #4
    SitePoint Member
    Join Date
    Nov 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    After I read your source code.
    At First forget about my previous comment.

    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


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •