Joomla 4. Компонент K2 и форк K2ForJ4 (18 янв 2024)

Если вас, как и меня, достало выслушивать (вычитывать) бесконечные обещания разработчика K2 опубликовать версию компонента K2 под Joomla 4 (без чего невозможно реализовать апгрейд from Joomla 3 to Joomla 4) - воспользуйтесь форком K2ForJ4. Который в данный момент установлен и без каких-либо проблем работает на этом веб-сайте.

Время от времени - и не так чтобы редко - на форуме звучат вопросы по нативному PHP... решили собирать их в этой ветке.

HTML Generate: Generate HTML from arrays

Больше
6 года 11 мес. назад - 6 года 11 мес. назад #1 от Aleksej
Aleksej создал тему: HTML Generate: Generate HTML from arrays
Мы с вами имеем возможность значительно упростить формирование HTML умного погодного информера, воспользовавшись готовым классом by Tony Frezza :

HTML Generate: Generate HTML from arrays
Description
This class can generate HTML from arrays.
It can add to a document tags of the supported types with a given list of tag attributes.
The class can set a random tag id, if none is specified. The tag can also be added to a parent tag given by id. The current tag id is returned.
The class can also generate the HTML for the whole document after it is composed.


Отличная штука, рекомендую. Всего-то и понадобится, что подключить html.php, который на момент написания поста выглядит следующим образом:

Code:
<?php # html class # coded by Tony Aldrin Fernandes Frezza # e-mail : frezzatony@gmail.com # year: 2017 class Html{ var $nodes = array(); /** * Arrays that can be edited in the class, or when in extended use, use array merge to add more values dynamically */ var $selfClosers = array('area','base','br','col','command','embed','hr','img','input','keygen','link','meta','param','source','track','wbr'); var $arrNoAttribute = array('tag','children','text','random_id','parent_id','no_attribute','options','input_type'); var $arrNoTabulate = array('option','button','label','textarea'); /** * Add nodes to html context. * * @param array $arrProp * @return integer id */ function add($arrProp = array()){ if(!sizeof($arrProp)){ return false; } if(!isset($arrProp['id'])){ $arrProp['id'] = self::getRandomId(); $arrProp['random_id'] = true; } //adds children to parent node, from id of parent node if(isset($arrProp['parent_id'])){ $this->nodes = $this->buildTree($arrProp); } else{ if(!(isset($arrProp['children']))){ $arrProp['children'] = array(); } array_push($this->nodes,$arrProp); } return $arrProp['id']; } /** * Generates the html and returns a string with all the content previously built. * * @return string html */ public function getHtml(){ $arrProp = func_get_args(); $arrTree = isset($arrProp[0]) ? $arrProp[0] : $this->nodes; $treeLevel = isset($arrProp[1]) ? $arrProp[1] : 0; $htmlReturn = ''; foreach($arrTree as $node){ $htmlReturn .= "\n".str_repeat("\t",$treeLevel); if(isset($node['tag'])){ $htmlReturn .= '<'.$node['tag'].' '; } foreach($node as $attribute=>$val){ $arrNoAttributes = $this->arrNoAttribute; if(isset($node['no_attribute'])){ $arrNoAttributes = array_merge($arrNoAttributes,$node['no_attribute']); } if(!in_array($attribute,$arrNoAttributes)){ if($attribute!='id' || ($attribute=='id' && !isset($node['random_id']))){ $htmlReturn .= $attribute . '="'; if(!is_array($val)){ $htmlReturn .= $val.'" '; } else if(is_array($val)){ foreach($val as $attr){ $htmlReturn.= $attr . ' '; } $htmlReturn .= '"'; } } } } if(isset($node['tag']) && !in_array($node['tag'],$this->selfClosers)){ $htmlReturn .= '>'; } if(isset($node['text'])){ $htmlReturn .= $node['text']; } if(isset($node['children']) && $node['children']){ $htmlReturn .= str_repeat("\t",$treeLevel); $htmlReturn .= $this->getHtml($node['children'],($treeLevel+1)); } $arrNoTabulates = $this->arrNoTabulate; if(isset($node['no_tabulate'])){ $arrNoTabulates = array_merge($arrNoTabulates,$node['no_tabulate']); } if(isset($node['tag']) && !in_array($node['tag'],$arrNoTabulates)){ $htmlReturn .="\n"; $htmlReturn .= str_repeat("\t",$treeLevel); } if(isset($node['tag']) && !in_array($node['tag'],$this->selfClosers)){ $htmlReturn .='</'.$node['tag'].'>'; } if(isset($node['tag']) && in_array($node['tag'],$this->selfClosers)){ $htmlReturn .= '/>'; } } return $htmlReturn; } /** * Reset the data. * The instantiated object can be reused to regenerate an html string. */ public function resetHtml(){ unset($this->nodes); $this->nodes = array(); } /** * PRIVATES, PROTECTEDS */ /** * Generate random ids. * Besides being used by the class, it can be useful when the class is extended * * @param integer $length * @return string random */ protected function getRandomId($length = 8){ return substr( md5(rand()), 0, $length); } /** * Adds child nodes inside parent nodes to generate html * * @return array htmlTree */ private function buildTree(){ $arrProp = func_get_args(); if(isset($arrProp[1])){ $arrTree = $arrProp[1]; } else{ $arrTree = $this->nodes; } foreach($arrTree as &$node){ if(isset($node['id']) && $node['id'] == $arrProp[0]['parent_id']){ if(!isset($node['children'])){ $node['children'] = array(); } unset($arrProp[0]['parent_id']); array_push($node['children'],$arrProp[0]); } else if(isset($node['children']) && $node['children']){ $node['children'] = $this->buildTree($arrProp[0],$node['children']); } } return $arrTree; } } ?>


Ну, а выводим в HTML показания погодного информера (вы можете использовать любую из показанных на страничке форума заготовок), например, следующим образом:

Code:
<?php $ip = $_SERVER['REMOTE_ADDR']; include("SxGeo.php"); $SxGeo = new SxGeo('SxGeoCity.dat'); $city = $SxGeo->get($ip); $loc_array = array( $city['city']['lat'], $city['city']['lon'] ); $api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; $num_of_days = 1; $loc_safe = array(); foreach ($loc_array as $loc) { $loc_safe[] = urlencode($loc); } $loc_string = implode(',', $loc_safe); $basicurl = sprintf('http://api.worldweatheronline.com/free/v2/weather.ashx?key=%s&q=%s&num_of_days=%s', $api_key, $loc_string, intval($num_of_days)); $xml_response = file_get_contents($basicurl); $xml = simplexml_load_string($xml_response); $ss = array(); foreach ($xml[0] as $name => $val) { foreach ($val as $name => $val) { $ss[$name] = $val; } } ?> <style type="text/css"> .title_weather { color: #006699; } </style> <div class="title_weather"> <script language="JavaScript"> var h=(new Date()).getHours(); if (h > 23 || h <7) document.write("<? echo 'Доброй ночи, ' . $city['city']['name_ru']; ?>"); if (h > 6 && h < 12) document.write("<? echo 'Доброе утро, ' . $city['city']['name_ru']; ?>"); if (h > 11 && h < 19) document.write("<? echo 'Добрый день, ' . $city['city']['name_ru']; ?>"); if (h > 18 && h < 24) document. write("<? echo 'Добрый вечер, ' . $city['city']['name_ru']; ?>"); </script> </div> <? include('html.php'); $html = new Html; $html->add(array( 'tag' => 'p', 'text' => '<img src="' . $xml->current_condition->weatherIconUrl . '"/>' )); $html->add(array( 'tag' => 'p', 'text' => $ss["date"] )); $html->add(array( 'tag' => 'div', 'text' => 'Координаты ' . $ss["query"] )); $html->add(array( 'tag' => 'div', 'text' => $city['city']['name_en'] )); $html->add(array( 'tag' => 'div', 'text' => $city['country']['iso'] )); $html->add(array( 'tag' => 'h4', 'text' => 'У вас сегодня:' )); $html->add(array( 'tag' => 'div', 'text' => 'Температура ' . $ss["temp_C"] . ' °C' )); $html->add(array( 'tag' => 'div', 'text' => 'Мин. температура сегодня ' . $ss["mintempC"] . ' °C' )); $html->add(array( 'tag' => 'div', 'text' => 'Макс. температура сегодня ' . $ss["maxtempC"] . ' °C' )); $html->add(array( 'tag' => 'div', 'text' => 'Скорость ветра ' . $ss["windspeedKmph"] . 'км/час' )); $html->add(array( 'tag' => 'div', 'text' => 'Направление ветра ' . $ss["winddir16Point"] )); $html->add(array( 'tag' => 'div', 'text' => 'Пасмурно ' . $ss["cloudcover"] . ' %' )); $html->add(array( 'tag' => 'div', 'text' => 'Давление ' . $ss["pressure"] . ' mb' )); $html->add(array( 'tag' => 'div', 'text' => 'Влажность ' . $ss["humidity"] . ' %' )); $html->add(array( 'tag' => 'div', 'text' => 'Осадки ' . $ss["precipMM"] . ' мм' )); $html->add(array( 'tag' => 'div', 'text' => 'Видимость на дорогах ' . $ss["visibility"] . ' км' )); $html->add(array( 'tag' => 'strong', 'text' => $ss["weatherDesc"] )); $html->add(array( 'tag' => 'div', 'text' => 'Восход солнца ' . $ss['astronomy']->sunrise )); $html->add(array( 'tag' => 'div', 'text' => 'Закат солнца ' . $ss['astronomy']->sunset )); $html->add(array( 'tag' => 'div', 'text' => 'Восход луны ' . $ss['astronomy']->moonrise )); $html->add(array( 'tag' => 'div', 'text' => 'Закат луны ' . $ss['astronomy']->moonset )); echo $html->getHtml(); ?>


Впрочем, всегда возможны. варианты. :)
Последнее редактирование: 6 года 11 мес. назад пользователем Aleksej.

Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.

Dev banner 3
Больше
6 года 2 мес. назад #2 от serge
serge ответил в теме HTML Generate: Generate HTML from arrays
Вместо
Code:
$basicurl = sprintf('http://api.worldweatheronline.com/free/v2/weather.ashx?key=%s&q=%s&num_of_days=%s', $api_key, $loc_string, intval($num_of_days));

следует использовать
Code:
$basicurl = sprintf('http://api.worldweatheronline.com/premium/v1/weather.ashx?key=%s&q=%s&num_of_days=%s', $api_key, $loc_string, intval($num_of_days));

т. к. все free API на WorldWeatherOnline себя исчерпали. У них там тоже кризис, ничего с этим не поделаешь. :)

А я смогу! - А поглядим! - А я упрямый!

Пожалуйста Войти или Регистрация, чтобы присоединиться к беседе.

Работает на Kunena форум