Помогите с переделкой скриптов работающих на PHP 5.2.x под PHP 5.3.x

evoll

Создатель
Регистрация
2 Авг 2009
Сообщения
38
Реакции
5
PHP:
<?php 
if(!defined("DNREAD")) exit(); 
global $db,$basepref,$api;

//задаем путь к файлу кеширования
$cache_file = "cache/currency.cache";
# Базовый URL скрипта на cbr.ru
$scripturl = 'http://www.cbr.ru/scripts/XML_dynamic.asp';

# Начальная дата для запроса  (сегодня - 2 дня(-172800) или 3 дня (-259200) или 9 дней(-777600))
$date_1=date('d/m/Y', time()-777600);

# Конечная дата (чтобы учитывать завтра добавьте параметр time()+86400)
$date_2=date('d/m/Y', time()+86400);

# Таким образом, мы получим данные либо за 2, либо за 3 последних дня.
# За 2 - если на "сегодня" курс еще не выставили, иначе - за 3

# Код валюты в архиве данных cbr.ru
$currency_code = array('R01235', 'R01239');
$currency_name = array('$','€');
if(time() >= time(1, 0, 0, date("m"), date("d"), date("Y")) && @filemtime($cache_file) < mktime(0, 0, 10, date("m"), date("d")-1, date("Y"))) 
{for($j=0; $j<count($currency_code); $j++){
    # URL для запроса данных
    $requrl = "{$scripturl}?date_req1={$date_1}&date_req2={$date_2}&VAL_NM_RQ={$currency_code[$j]}";

    $doc = file($requrl);
    $doc = implode($doc, '');

    # инициализируем массив
    $r = array();

    # ищем <ValCurs>...</ValCurs>
    if(preg_match("/<ValCurs.*?>(.*?)<\/ValCurs>/is", $doc, $m))
        # а потом ищем все вхождения <Record>...</Record>
        preg_match_all("/<Record(.*?)>(.*?)<\/Record>/is", $m[1], $r, PREG_SET_ORDER);

    $m = array();    # его уже использовали, реинициализируем
    $d = array();    # этот тоже проинициализируем

    # Сканируем на предмет самых нужных цифр
    for($i=0; $i<count($r); $i++) {
        if(preg_match("/Date=\"(\d{2})\.(\d{2})\.(\d{4})\"/is", $r[$i][1],$m)) {
            $dv = "{$m[1]}/{$m[2]}/{$m[3]}"; # Приводим дату в норм. вид
            if(preg_match("/<Nominal>(.*?)<\/Nominal>.*?<Value>(.*?)<\/Value>/is", $r[$i][2], $m)) {
                $m[2] = preg_replace("/,/",".",$m[2]);
                $d[] = array($dv, $m[1], $m[2]);
                }
            }
        }

    $last = array_pop($d);                # последний известный день
    $prev = array_pop($d);                # предпосл. известный день
    $date = $last[0];                    # отображаемая дата
    $rate = sprintf("%.2f",$last[2]);        # отображаемый курс
    # отображаемое изменение курса, например, "+0.02"
    $delta = (($last[2]>$prev[2])?"<font color=green>+":"<font color=red>").sprintf("%.2f</font>",$last[2]-$prev[2]);

     $string = $string."<b>1 ".$currency_name[$j]."</b> = {$rate} руб ({$delta})<BR>";
     @unlink($cache_file);
        $fp = @fopen($cache_file, 'x');
        fwrite($fp, $string);
        fclose($fp);
}
}
//извлекаем из кеша результат
$fp = @fopen($cache_file, 'r');
$content = fread($fp, filesize($cache_file));
fclose($fp);
//выводим результат
return $api->siteuni($content);

?>
выкидывает сообщение Notice: Undefined variable: string in \www\city\block\b-!KursValut!.php on line 59 Call Stack

сама эта строчка
PHP:
     $string = $string."<b>1 ".$currency_name[$j]."</b> = {$rate} руб ({$delta})<BR>";

скрипт работает.......но нотисы при обновлении кеша напрягают
 
Система ругается на неопределенную переменную! Для начала попробуйте заменить знак евро его html-сущностью ( &euro; )
$currency_name = array('$','&euro;');
ну а саму 59ю строку приведите как то к одному стилистическому виду:
PHP:
  $string = $string."<b>1 ".$currency_name[$j]."</b> = ".$rate." руб (".$delta.")<br>";
 
так же. значение считывает но при новом значении выкидывает тот же нотиф. при этом значения считывает
Но нашел интересную закономерность. Если в строке
PHP:
$string = $string."<b>1 ".$currency_name[$j]."</b> = ".$rate." руб (".$delta.")<br>";
убрать параметр $string. т.е. получаем такую строку
PHP:
$string = "<b>1 ".$currency_name[$j]."</b> = ".$rate." руб (".$delta.")<br>";
то все обрабатывается без нотифов но на выходе только получаем курс доллара
 
Это логично... при первой прокрутке цикла, переменная $string как раз и не определена...
Сделайте так:
PHP:
$string .= "<b>1 ".$currency_name[$j]."</b> = ".$rate." руб (".$delta.")<br>";
для того, чтобы отобразить все данные.
 
В скрипте, перед циклом
Код:
for($j=0; $j<count($currency_code); $j++){
объявите свою $string = '';
Сделайте так
Код:
    $string = '';
    for($j=0; $j<count($currency_code); $j++){
Т.е. перед циклом необходимо объявить переменную и присвоить ей пустое значение.
 
спасибо помогло) вот помогите еще с одним скриптиком. тут используется в оригинале функция eregi() а вот в 5.3.6 уже она не работает. Советуют заменить на preg_match ....но она как то не работает(((
сам скрипт в оригинале:
PHP:
<?php
/*
=====================================================
Блок погоды с сайта  http://gismeteo.ru для CMS Danneo  053
=====================================================
При использовании  ссылка на сайт http://artdiz.com Обязательна!
=====================================================
http://artdiz.com/
=====================================================
 Файл:  b-weather.php
-----------------------------------------------------
 Назначение:  Weather парсер погоды
=====================================================
*/
if(!defined("DNREAD")) exit(); 
global $db,$basepref,$api;
$bt = '';
$w = new Weather; 
$w->ConnectCache('34122_1.xml'); //Собираем информацию и КЕШруем её, ID города можно узнать по адрему http://informer.gismeteo.ru/xml.html?index=27612%CC%EE%F1%EA%E2%E0&&lang=ru
$bt.='<b style=\"font-size:14px;color: #b30935;\">' .$w->city. '</b>';
$bt.= $w->weather;
/* Раскоментируйте если нужен еще один населенный пункт Учитывайте нагрузку на сервер 
$bt.='<br/><br/>';
$w->ConnectCache('33837_1.xml'); //Чтобы установить время в течение которого скрипт будет обновляться и КЕШировать данные, можно изменив $w->ConnectCache('26063_1.xml'); на $w->ConnectCache('26063_1.xml','3600'); в таком случаи скрипт будет обновлять данные ежечасно,  по умолчанию она стоит 7200, т.е. данные будут обновляться каждые 2 часа
$bt.='<b style=\"font-size:14px;color: #b30935;\">' .$w->city. '</b>';
$bt.= $w->weather;
 */
/*Если нужно еще добавить город то добовляем этот код, меняем 31960_1.xml на код нужного вам города 
$w->Connect('31960_1.xml'); 
$bt.=  $w->city;
$bt.=  $w->weather;
 */
/*
$w->Connect('31960_1.xml'); 
$bt.=  $w->city;
$bt.=  $w->weather;
$w->Connect('88999_1.xml'); 
$bt.=  $w->city;
$bt.=  $w->weather;
*/
class Weather {
	var $city;
	var $weather;
	var $encode = 'windows-1251'; // Кодировка в которой будут выводиться данные
	var $patchimg = 'up/weather/'; 
	var $patchcache = 'cache/cache_weather/'; 
	//Подключаемся без использования КЕШа,  Этот метод крайне не рекомендую использовать только при постоянных ошибках скрипта
	function Connect($url, $encode){
		$url = 'http://informer.gismeteo.ru/xml/'.$url; 
		$content = @file_get_contents($url); 
		$content = str_replace(array(''.chr(11).'',''.chr(13).'',''.chr(10).'',''.chr(9).'','\n','\r','/',' '),array(''),$content); 
		$this->city=$this->pCity($content); 
		$this->weather=$this->Parser($content);
	}
	//Подключаемся с использованием КЕШа, т.е. данные будут сохраняться в файл.  
	function ConnectCache($url, $expire =7200){
		$mtime = 0;
		$file_cacheid = $this->patchcache . md5($url); 
		if($file_cacheid) $s=true; else $s=false; 
        if(!file_exists($file_cacheid)) $s=false; 
        if(!($mtime = @filemtime($file_cacheid))) $s=false; 
        if(($mtime + $expire) < time()){ 
            @unlink($file_cacheid); 
            $s=false;
        }
        else {
           $s=true;
        }
		if ((!$s)) { 
			if(file_exists($file_cacheid))
				@unlink($file_cacheid); 
			$url = 'http://informer.gismeteo.ru/xml/'.$url; 
			$content = file_get_contents($url);
			$content = str_replace(array(''.chr(11).'',''.chr(13).'',''.chr(10).'',''.chr(9).'','\n','\r','/',' '),array(''),$content);
			$this->city=$this->pCity($content);
			$this->weather=$this->Parser($content);
			if($fp = @fopen($file_cacheid, 'w')) {
                fwrite($fp, ''.$this->city.'|'.$this->weather.'|'); 
                fclose($fp); 
            }
            else {
                die('Unable to write cache.');
            }
		} else {
			$fp = @fopen($file_cacheid, 'r'); 
			$p = explode('|',fread($fp, filesize($file_cacheid))); 
            fclose($fp);
			if ($this->encode !== 'windows-1251'){
			$this->city = iconv ("windows-1251", $this->encode, $p[0]); 
			$this->weather = iconv ("windows-1251", $this->encode, $p[1]); 
		}
				else{
			$this->city = $p[0]; 
			$this->weather = $p[1]; 
		}
		}
	}
	function pCity($content){
		$str = "<TOWNindex=\"(.*)\"sname=\"(.*)\"latitude=\"(.*)\"longitude=\"(.*)\">";
		if (eregi($str,$content,$out)){
			return urldecode($out[2]);
		} else return 'Unknow';
	}
	function Parser($content){
		if ($content){
			$str='<FORECASTday="([0-9]{1,2})"month="([0-9]{1,2})"year="([0-9]{4})"hour="([0-9]{1,2})"tod="([0-9]{1})"predict="([0-9]{1,4})"weekday="([0-9]{1})"><PHENOMENAcloudiness="([0-3])"precipitation="([0-9]{1,2})"rpower="([0-1])"spower="([0-1])"><PRESSUREmax="([0-9]{1,4})"min="([0-9]{1,4})"><TEMPERATUREmax="([-,0-9]{1,3})"min="([-,0-9]{1,4})"><WINDmin="([0-9]{1,4})"max="([0-9]{1,4})"direction="([0-9]{1})"><RELWETmax="([0-9]{1,4})"min="([0-9]{1,4})"><HEATmin="([-,0-9]{1,4})"max="([-,0-9]{1,4})"><FORECAST>'.
			'<FORECASTday="([0-9]{1,2})"month="([0-9]{1,2})"year="([0-9]{4})"hour="([0-9]{1,2})"tod="([0-9]{1})"predict="([0-9]{1,4})"weekday="([0-9]{1})"><PHENOMENAcloudiness="([0-3])"precipitation="([0-9]{1,2})"rpower="([0-1])"spower="([0-1])"><PRESSUREmax="([0-9]{1,4})"min="([0-9]{1,4})"><TEMPERATUREmax="([-,0-9]{1,4})"min="([-,0-9]{1,4})"><WINDmin="([0-9]{1,4})"max="([0-9]{1,4})"direction="([0-9]{1})"><RELWETmax="([0-9]{1,4})"min="([0-9]{1,4})"><HEATmin="([-,0-9]{1,4})"max="([-,0-9]{1,4})"><FORECAST>'.
			'<FORECASTday="([0-9]{1,2})"month="([0-9]{1,2})"year="([0-9]{4})"hour="([0-9]{1,2})"tod="([0-9]{1})"predict="([0-9]{1,4})"weekday="([0-9]{1})"><PHENOMENAcloudiness="([0-3])"precipitation="([0-9]{1,2})"rpower="([0-1])"spower="([0-1])"><PRESSUREmax="([0-9]{1,4})"min="([0-9]{1,4})"><TEMPERATUREmax="([-,0-9]{1,4})"min="([-,0-9]{1,4})"><WINDmin="([0-9]{1,4})"max="([0-9]{1,4})"direction="([0-9]{1})"><RELWETmax="([0-9]{1,4})"min="([0-9]{1,4})"><HEATmin="([-,0-9]{1,4})"max="([-,0-9]{1,4})"><FORECAST>'.
			'<FORECASTday="([0-9]{1,2})"month="([0-9]{1,2})"year="([0-9]{4})"hour="([0-9]{1,2})"tod="([0-9]{1})"predict="([0-9]{1,4})"weekday="([0-9]{1})"><PHENOMENAcloudiness="([0-3])"precipitation="([0-9]{1,2})"rpower="([0-1])"spower="([0-1])"><PRESSUREmax="([0-9]{1,4})"min="([0-9]{1,4})"><TEMPERATUREmax="([-,0-9]{1,4})"min="([-,0-9]{1,4})"><WINDmin="([0-9]{1,4})"max="([0-9]{1,4})"direction="([0-9]{1})"><RELWETmax="([0-9]{1,4})"min="([0-9]{1,4})"><HEATmin="([-,0-9]{1,4})"max="([-,0-9]{1,4})"><FORECAST>';
			if (eregi($str,$content,$out)){
				return $this->arr($out);
			} else return ' Ошибка в данных сайта gismeteo.ru! ';
		} else return 'Ошибка! Соединения с '.$url.'';
	}
	function imgcloud($n){
		$n=ceil($n);
		$cloudiness=array(
		'0' => "<img src=".$this->patchimg."0".(($n=='0' || $n=='4')?'_night':'').".gif style=\"float:left;margin-top:5px;\" alt=\"Ясно\" title=\"Ясно\">", 
		'1' => "<img src=".$this->patchimg."1".(($n=='0' || $n=='4')?'_night':'').".gif style=\"float:left;margin-top:5px;\" alt=\"Малооблачно\" title=\"Малооблачно\">", 
		'2' => "<img src=".$this->patchimg."2".(($n=='0' || $n=='4')?'_night':'').".gif style=\"float:left;margin-top:5px;\" alt=\"Облачно\" title=\"Облачно\">",
		'3' => "<img src=".$this->patchimg."3.gif style=\"float:left;margin-top:5px;\" alt=\"Пасмурно\" title=\"Пасмурно\">");
		return $cloudiness;
	}
	function imgprecip($n){
		$n=ceil($n);
		$precipitation=array(
		'4' => "<img src=".$this->patchimg."4.gif style=\"float:left;margin-top:5px;\" alt=\"Дождь\" title=\"Дождь\">" ,
		'5' => "<img src=".$this->patchimg."5.gif style=\"float:left;margin-top:5px;\" alt=\"Ливень\" title=\"Ливень\">",
		'6' => "<img src=".$this->patchimg."6.gif style=\"float:left;margin-top:5px;\" alt=\"Снег\" title=\"Снег\">",
		'7' => "<img src=".$this->patchimg."6.gif style=\"float:left;margin-top:5px;\" alt=\"Снег\" title=\"Снег\">",
		'8' => "<img src=".$this->patchimg."8.gif style=\"float:left;margin-top:5px;\" alt=\"Гроза\" title=\"Гроза\">",
		'9' => "<img src=".$this->patchimg."9".(($n=='0' || $n=='4')?'_night':'').".gif style=\"float:left;margin-top:5px;\" alt=\"нет данных\" title=\"нет данных\">",
		'10' => "<img src=".$this->patchimg."10".(($n=='0' || $n=='4')?'_night':'').".gif style=\"float:left;margin-top:5px;\" alt=\"Ясно\" title=\"Ясно\">");
		return $precipitation;
	}
	function arr($out){
		$month_array = array( '1' => 'января' , '2' => 'февраля' , '3' => 'марта' , '4' => 'апреля' , '5' => 'мая' , '6' => 'июня' , '7' => 'июля' ,
		'8' => 'августа' , '9' => 'сентября' , '10' => 'октября' , '11' => 'ноября' , '12' => 'декабря' );
		$tod = array( '0' => 'Ночью' , '1' => 'Утром' , '2' => 'Днем' , '3' => 'Вечером' , '4' => 'Ночью' );
		$rpower = array( '0' =>' возможен дождь/снег' , '1' => ' дождь/снег' );
		$spower = array( '0' =>' возможна гроза', '1' => ' гроза' );
		$direction = array( '0' => 'северный' , '1' => 'северо-восточный' , '2' => 'восточный' , '3' => 'юго-восточный' , '4' => 'южный' , '5' => 'юго-западный' ,
		'6' => 'западный' , '7' => 'северо-западный' );
		$direction = array( '0' => 'северный' , '1' => 'северо-восточный' , '2' => 'восточный' , '3' => 'юго-восточный' , '4' => 'южный' , '5' => 'юго-западный' ,
		'6' => 'западный' , '7' => 'северо-западный' );
		$weekday = array( '1' => 'воскресенье' , '2' => 'понедельник' , '3' => 'вторник' , '4' => 'среду' , '5' => 'четверг' , '6' => 'пятницу' , '7' => 'субботу' );
		$day1 = $out[1]; 
		$month1 = $month_array[ceil($out[2])]; 
		$tod1 = $tod[ceil($out[5])]; 
		$weekday1 = $weekday[$out[7]]; 
		$rpower1 = $rpower[$out[10]];
		$spower1 = $spower[$out[11]]; 
		if (($out[8] < 4) and ($out[8] >= 0) and ($out[9]=='10')) {
			$cloudiness=$this->imgcloud($out[5]);
			$cloudiness1 = $cloudiness[$out[8]]; 
		} else {
			$precipitation=$this->imgprecip($out[5]);
			$precipitation1 = $precipitation[$out[9]]; 
		}
		$pressureMAX1 = $out[12]; 
		$pressureMIN1 = $out[13];
		$tempMIN1 = $out[15]; 
		$tempMAX1 = $out[14]; 
		$windMIN1 = $out[16];
		$windMAX1 = $out[17]; 
		$direction1 = $direction[$out[18]];
		$relwenMIN1 = $out[20]; 
		$relwenMAX1 = $out[19];
		$heatMIN1 = $out[21]; 
		$heatMAX1 = $out[22]; 
		$day2 = $out[23];
		$month2 = $month_array[ceil($out[24])];
		$tod2 = $tod[ceil($out[27])];
		$weekday2 = $weekday[$out[29]];
		$rpower2 = $rpower[$out[32]];
		$spower2 = $spower[$out[33]];
		if (($out[30] < 4) and ($out[30] >= 0) and ($out[31]=='10')) { 
			$cloudiness=$this->imgcloud($out[27]);
			$cloudiness2 = $cloudiness[$out[30]];
		} else {
			$precipitation=$this->imgprecip($out[27]);
			$precipitation2 = $precipitation[$out[31]];
		}
		$pressureMIN2 = $out[35];
		$pressureMAX2 = $out[34];
		$tempMIN2 = $out[37];
		$tempMAX2 = $out[36];
		$windMIN2 = $out[38];
		$windMAX2 = $out[39];
		$direction2 = $direction[$out[40]];
		$relwenMIN2 = $out[42];
		$relwenMAX2 = $out[41];
		$heatMIN2 = $out[43]; 
		$heatMAX2 = $out[44]; 
		$day3 = $out[45];
		$month3 = $month_array[ceil($out[46])];
		$tod3 = $tod[ceil($out[49])];
		$weekday3 = $weekday[$out[51]];
		$rpower3 = $rpower[$out[54]];
		$spower3 = $spower[$out[55]];
		if (($out[52] < 4) and ($out[52] >= 0) and ($out[53]=='10')) {
			$cloudiness=$this->imgcloud($out[49]);
			$cloudiness3 = $cloudiness[$out[52]];
		} else {
			$precipitation=$this->imgprecip($out[49]);
			$precipitation3 = $precipitation[$out[53]];
		}
		$pressureMIN3 = $out[57];
		$pressureMAX3 = $out[56];
		$tempMIN3 = $out[59];
		$tempMAX3 = $out[58];
		$windMIN3 = $out[60];
		$windMAX3 = $out[61];
		$direction3 = $direction[$out[62]];
		$relwenMIN3 = $out[64];
		$relwenMAX3 = $out[63];
		$heatMIN3 = $out[65];
		$heatMAX3 = $out[66];
		$day4 = $out[67]; 
		$month4 = $month_array[ceil($out[68])]; 
		$tod4 = $tod[ceil($out[71])]; 
		$weekday4 = $weekday[$out[73]]; 
		$rpower4 = $rpower[$out[76]]; 
		$spower4 = $spower[$out[77]]; 
		if (($out[74] < 4) and ($out[74] >= 0) and ($out[75]=='10')) {
			$cloudiness=$this->imgcloud($out[71]);
			$cloudiness4 = $cloudiness[$out[74]]; 
		} else {
			$precipitation=$this->imgprecip($out[71]);
			$precipitation4 = $precipitation[$out[75]]; 
		}
		$pressureMAX4 = $out[79]; 
		$pressureMIN4 = $out[78]; 
		$tempMIN4 = $out[81]; 
		$tempMAX4 = $out[80]; 
		$windMIN4 = $out[82]; 
		$windMAX4 = $out[83]; 
		$direction4 = $direction[$out[84]];
		$relwenMIN4 = $out[86]; 
		$relwenMAX4 = $out[85]; 
		$heatMIN4 = $out[87]; 
		$heatMAX4 = $out[88]; 
		$content .= "<div style=\"border-top:1px dashed #999999;\"> <b style=\"font-size:12px;color: #8f91a1;\">".$day1." ".$month1." в ".$weekday1."</b><br />".$cloudiness1." ".$precipitation1."<b style=\"font-size:12px; color: #8a102f;\">".$tod1." </b> <br /><b style=\"font-size:12px;\"> <span title=\"комфорт ".$heatMIN1."..".$heatMAX1."°C\">".$tempMIN1."°C...".$tempMAX1."°C</span></b><br /><span style=\"font-size:10px;\">Атм.дав.".$pressureMIN1."-".$pressureMAX1."мм рт.ст.</span><br /><span style=\"font-size:10px;\">Влажность воздуха ".$relwenMIN1."-".$relwenMAX1."%</span><br /> <span style=\"font-size:10px;\">Ветер ".$windMIN1."-".$windMAX1."м/c ".$direction1."</span><br /></div>";
		$content .= "<div style=\"border-top:1px dashed #999999;\"><b style=\"font-size:12px;color: #8f91a1;\">".$day2." ".$month2." в ".$weekday2."</b><br />".$cloudiness2." ".$precipitation2." <b style=\"font-size:12px; color: #8a102f;\">".$tod2." </b> <br /><b style=\"font-size:12px;\"> <span title=\"комфорт ".$heatMIN2."..".$heatMAX2."°C\">".$tempMIN2."°C...".$tempMAX2."°C</span></b><br /><span style=\"font-size:10px;\">Атм.дав.".$pressureMIN2."-".$pressureMAX2."мм рт.ст.</span><br /><span style=\"font-size:10px;\">Влажность воздуха ".$relwenMIN2."-".$relwenMAX2."%</span><br /> <span style=\"font-size:10px;\">Ветер ".$windMIN2."-".$windMAX2."м/c ".$direction2."</span><br /></div>";
		$content .= "<div style=\"border-top:1px dashed #999999;border-bottom:1px dashed #999999;\"><b style=\"font-size:12px;color: #8f91a1;\">".$day3." ".$month3." в ".$weekday3."</b><br />".$cloudiness3." ".$precipitation3." <b style=\"font-size:12px; color: #8a102f;\">".$tod3."</b><br /><b style=\"font-size:12px;\"> <span title=\"комфорт ".$heatMIN3."..".$heatMAX3."°C\">".$tempMIN3."°C...".$tempMAX3."°C</span></b><br /><span style=\"font-size:10px;\">Атм.дав.".$pressureMIN3."-".$pressureMAX3."мм рт.ст.</span><br /><span style=\"font-size:10px;\">Влажность воздуха ".$relwenMIN3."-".$relwenMAX3."%</span><br /> <span style=\"font-size:10px;\">Ветер ".$windMIN3."-".$windMAX3."м/c ".$direction3."</span><br /></div>";
		$content .= "<div style=\"border-bottom:1px dashed #999999;\"><b style=\"font-size:12px;color: #8f91a1;\">".$day4." ".$month4." в ".$weekday4."</b><br />".$cloudiness4." ".$precipitation4."<b style=\"font-size:12px; color: #8a102f;\">".$tod4." </b><br /><b style=\"font-size:12px;\"><span title=\"комфорт ".$heatMIN4."..".$heatMAX4."°C\">".$tempMIN4."°C...".$tempMAX4."°C</span></b><br /><span style=\"font-size:10px;\">Атм.дав.".$pressureMIN4."-".$pressureMAX4."мм рт.ст.</span><br /><span style=\"font-size:10px;\">Влажность воздуха ".$relwenMIN4."-".$relwenMAX4."%</span><br /> <span style=\"font-size:10px;\">Ветер ".$windMIN4."-".$windMAX4."м/c ".$direction4."</span><br /></div>";
		return $content; 
	}
}
return $api->siteuni($bt);
?>
Идеи есть как eregi заменить корректно на preg_match?
____________________________________________________________
Так вроде заменил в итоге вышло вот такое примерно

PHP:
	function pCity($content){
		$str = "<TOWNindex=\"(.*)\"sname=\"(.*)\"latitude=\"(.*)\"longitude=\"(.*)\">";
		if (preg_match('/'.$str.'/i',$content,$out)){
			return urldecode($out[2]);
		} else return 'Unknow';
	}

	function Parser($content){
		if ($content){
			$str='<FORECASTday="([0-9]{1,2})"month="([0-9]{1,2})"year="([0-9]{4})"hour="([0-9]{1,2})"tod="([0-9]{1})"predict="([0-9]{1,4})"weekday="([0-9]{1})"><PHENOMENAcloudiness="([0-3])"precipitation="([0-9]{1,2})"rpower="([0-1])"spower="([0-1])"><PRESSUREmax="([0-9]{1,4})"min="([0-9]{1,4})"><TEMPERATUREmax="([-,0-9]{1,3})"min="([-,0-9]{1,4})"><WINDmin="([0-9]{1,4})"max="([0-9]{1,4})"direction="([0-9]{1})"><RELWETmax="([0-9]{1,4})"min="([0-9]{1,4})"><HEATmin="([-,0-9]{1,4})"max="([-,0-9]{1,4})"><FORECAST>'.
			'<FORECASTday="([0-9]{1,2})"month="([0-9]{1,2})"year="([0-9]{4})"hour="([0-9]{1,2})"tod="([0-9]{1})"predict="([0-9]{1,4})"weekday="([0-9]{1})"><PHENOMENAcloudiness="([0-3])"precipitation="([0-9]{1,2})"rpower="([0-1])"spower="([0-1])"><PRESSUREmax="([0-9]{1,4})"min="([0-9]{1,4})"><TEMPERATUREmax="([-,0-9]{1,4})"min="([-,0-9]{1,4})"><WINDmin="([0-9]{1,4})"max="([0-9]{1,4})"direction="([0-9]{1})"><RELWETmax="([0-9]{1,4})"min="([0-9]{1,4})"><HEATmin="([-,0-9]{1,4})"max="([-,0-9]{1,4})"><FORECAST>'.
			'<FORECASTday="([0-9]{1,2})"month="([0-9]{1,2})"year="([0-9]{4})"hour="([0-9]{1,2})"tod="([0-9]{1})"predict="([0-9]{1,4})"weekday="([0-9]{1})"><PHENOMENAcloudiness="([0-3])"precipitation="([0-9]{1,2})"rpower="([0-1])"spower="([0-1])"><PRESSUREmax="([0-9]{1,4})"min="([0-9]{1,4})"><TEMPERATUREmax="([-,0-9]{1,4})"min="([-,0-9]{1,4})"><WINDmin="([0-9]{1,4})"max="([0-9]{1,4})"direction="([0-9]{1})"><RELWETmax="([0-9]{1,4})"min="([0-9]{1,4})"><HEATmin="([-,0-9]{1,4})"max="([-,0-9]{1,4})"><FORECAST>'.
			'<FORECASTday="([0-9]{1,2})"month="([0-9]{1,2})"year="([0-9]{4})"hour="([0-9]{1,2})"tod="([0-9]{1})"predict="([0-9]{1,4})"weekday="([0-9]{1})"><PHENOMENAcloudiness="([0-3])"precipitation="([0-9]{1,2})"rpower="([0-1])"spower="([0-1])"><PRESSUREmax="([0-9]{1,4})"min="([0-9]{1,4})"><TEMPERATUREmax="([-,0-9]{1,4})"min="([-,0-9]{1,4})"><WINDmin="([0-9]{1,4})"max="([0-9]{1,4})"direction="([0-9]{1})"><RELWETmax="([0-9]{1,4})"min="([0-9]{1,4})"><HEATmin="([-,0-9]{1,4})"max="([-,0-9]{1,4})"><FORECAST>';
			if (preg_match('/'.$str.'/i',$content,$out)){
				return $this->arr($out);
			} else return ' Ошибка в данных сайта gismeteo.ru! ';
		} else return 'Ошибка! Соединения с '.$url.'';
	}

Парсить начало но засыпало нотифами уже вот какими
HTML:
 Notice: Undefined variable: precipitation1 in D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php on line 278
Call Stack
#	Time	Memory	Function	Location
1	0.0015	399368	{main}( )	..\index.php:0
2	0.0362	1451768	include( 'D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php' )	..\index.php:160
3	0.0362	1452384	Weather->ConnectCache( )	..\b-!Weather.php:22
4	0.1355	1456648	Weather->Parser( )	..\b-!Weather.php:81
5	0.1356	1468976	Weather->arr( )	..\b-!Weather.php:123


( ! ) Notice: Undefined variable: content in D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php on line 278
Call Stack
#	Time	Memory	Function	Location
1	0.0015	399368	{main}( )	..\index.php:0
2	0.0362	1451768	include( 'D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php' )	..\index.php:160
3	0.0362	1452384	Weather->ConnectCache( )	..\b-!Weather.php:22
4	0.1355	1456648	Weather->Parser( )	..\b-!Weather.php:81
5	0.1356	1468976	Weather->arr( )	..\b-!Weather.php:123


( ! ) Notice: Undefined variable: precipitation2 in D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php on line 279
Call Stack
#	Time	Memory	Function	Location
1	0.0015	399368	{main}( )	..\index.php:0
2	0.0362	1451768	include( 'D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php' )	..\index.php:160
3	0.0362	1452384	Weather->ConnectCache( )	..\b-!Weather.php:22
4	0.1355	1456648	Weather->Parser( )	..\b-!Weather.php:81
5	0.1356	1468976	Weather->arr( )	..\b-!Weather.php:123


( ! ) Notice: Undefined variable: precipitation3 in D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php on line 280
Call Stack
#	Time	Memory	Function	Location
1	0.0015	399368	{main}( )	..\index.php:0
2	0.0362	1451768	include( 'D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php' )	..\index.php:160
3	0.0362	1452384	Weather->ConnectCache( )	..\b-!Weather.php:22
4	0.1355	1456648	Weather->Parser( )	..\b-!Weather.php:81
5	0.1356	1468976	Weather->arr( )	..\b-!Weather.php:123


( ! ) Notice: Undefined variable: precipitation4 in D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php on line 281
Call Stack
#	Time	Memory	Function	Location
1	0.0015	399368	{main}( )	..\index.php:0
2	0.0362	1451768	include( 'D:\VertrigoServ\www\city-vrn.ru\block\b-!Weather.php' )	..\index.php:160
3	0.0362	1452384	Weather->ConnectCache( )	..\b-!Weather.php:22
4	0.1355	1456648	Weather->Parser( )	..\b-!Weather.php:81
5	0.1356	1468976	Weather->arr( )	..\b-!Weather.php:123

вот этот кусок на который он материт в исходно скрипте

PHP:
		/*Здесь вы можете убрать переменные которые вам не нужны или изменить вид их вывода.*/
		$content .= "<div style=\"border-top:1px dashed #999999;\"> <b style=\"font-size:12px;color: #8f91a1;\">".$day1." ".$month1." в ".$weekday1."</b><br />".$cloudiness1." ".$precipitation1."<b style=\"font-size:12px; color: #8a102f;\">".$tod1." </b> <br /><b style=\"font-size:12px;\"> <span title=\"комфорт ".$heatMIN1."..".$heatMAX1."°C\">".$tempMIN1."°C...".$tempMAX1."°C</span></b><br /><span style=\"font-size:10px;\">Атм.дав.".$pressureMIN1."-".$pressureMAX1."мм рт.ст.</span><br /><span style=\"font-size:10px;\">Влажность воздуха ".$relwenMIN1."-".$relwenMAX1."%</span><br /> <span style=\"font-size:10px;\">Ветер ".$windMIN1."-".$windMAX1."м/c ".$direction1."</span><br /></div>";
		$content .= "<div style=\"border-top:1px dashed #999999;\"><b style=\"font-size:12px;color: #8f91a1;\">".$day2." ".$month2." в ".$weekday2."</b><br />".$cloudiness2." ".$precipitation2." <b style=\"font-size:12px; color: #8a102f;\">".$tod2." </b> <br /><b style=\"font-size:12px;\"> <span title=\"комфорт ".$heatMIN2."..".$heatMAX2."°C\">".$tempMIN2."°C...".$tempMAX2."°C</span></b><br /><span style=\"font-size:10px;\">Атм.дав.".$pressureMIN2."-".$pressureMAX2."мм рт.ст.</span><br /><span style=\"font-size:10px;\">Влажность воздуха ".$relwenMIN2."-".$relwenMAX2."%</span><br /> <span style=\"font-size:10px;\">Ветер ".$windMIN2."-".$windMAX2."м/c ".$direction2."</span><br /></div>";
		$content .= "<div style=\"border-top:1px dashed #999999;border-bottom:1px dashed #999999;\"><b style=\"font-size:12px;color: #8f91a1;\">".$day3." ".$month3." в ".$weekday3."</b><br />".$cloudiness3." ".$precipitation3." <b style=\"font-size:12px; color: #8a102f;\">".$tod3."</b><br /><b style=\"font-size:12px;\"> <span title=\"комфорт ".$heatMIN3."..".$heatMAX3."°C\">".$tempMIN3."°C...".$tempMAX3."°C</span></b><br /><span style=\"font-size:10px;\">Атм.дав.".$pressureMIN3."-".$pressureMAX3."мм рт.ст.</span><br /><span style=\"font-size:10px;\">Влажность воздуха ".$relwenMIN3."-".$relwenMAX3."%</span><br /> <span style=\"font-size:10px;\">Ветер ".$windMIN3."-".$windMAX3."м/c ".$direction3."</span><br /></div>";
		$content .= "<div style=\"border-bottom:1px dashed #999999;\"><b style=\"font-size:12px;color: #8f91a1;\">".$day4." ".$month4." в ".$weekday4."</b><br />".$cloudiness4." ".$precipitation4."<b style=\"font-size:12px; color: #8a102f;\">".$tod4." </b><br /><b style=\"font-size:12px;\"><span title=\"комфорт ".$heatMIN4."..".$heatMAX4."°C\">".$tempMIN4."°C...".$tempMAX4."°C</span></b><br /><span style=\"font-size:10px;\">Атм.дав.".$pressureMIN4."-".$pressureMAX4."мм рт.ст.</span><br /><span style=\"font-size:10px;\">Влажность воздуха ".$relwenMIN4."-".$relwenMAX4."%</span><br /> <span style=\"font-size:10px;\">Ветер ".$windMIN4."-".$windMAX4."м/c ".$direction4."</span><br /></div>";
		return $content;
 
Если не критично, то на нотисы можете не обращать внимания.
А вот если хочется порядка, то необходимо инициализировать эти переменные перед их использованием.
В Вашем случае нотисы выскакивают на: precipitation1, content, precipitation2, precipitation3 и precipitation4.
Т.е. необходимо поступить также, как и в первом Вашем вопросе.
В методе arr($out) в самом его начале идет инициализация переменных
Код:
$month_array = array( '1' => 'января' ....
На сколько я понял, то это все переменные строкового типа, тогда в любом месте в начале этого метода до первого if - в Вашем случае это:
Код:
if (($out[8] < 4) and ($out[8] >= 0) and ($out[9]=='10')) {
добавьте
Код:
$content = '';
$precipitation1 = '';
$precipitation2 = '';
$precipitation3 = '';
$precipitation4 ='';

Как-то так.
 
переменные инициализировал.......но..... почему то стало отваливатся кеширование запросов(
 
обновил пхп до 5.3 полезли проблемы, часть решил, а вот что делать с вот этим не знаю и быстро найти не получаецо
PHP:
if ($i == $selected)
{
$buffer .= '<option value="'.$i .'" selected>'.$source[$i] .'</option>';
continue;
}
else
{
$buffer .= '<option value="'.$i .'">'.$source[$i] .'</option>';
continue;
}
скрипт выполняется до первого закрытия скобки, дальше остальной код выводится как обычный штмл
'.$source[$i] .'</option>';
continue;
}
else
{
$buffer .= '<option value="'.$i .'">'.$source[$i] .'</option>';
continue;
}
как пофиксить это дело?


разобрался... горе программер сэкономил... вместо <?php написал просто <?
а я тут голову ломаю))))
 
Назад
Сверху