Архив

Публикации с меткой ‘PHP’
9 ноября 2017 Нет комментариев

Используются плагины: AMP for WP — Accelerated Mobile Pages for WordPress, WP-GeSHi-Highlight.
Синтаксис внутри pre подсвечиваться конечно не будет.
В файл functions.php активной темы:
</pre > заменить на </pre> т.е. без пробела

function echapcode($a){
	return "<pre $a[1]>".htmlspecialchars($a[2])."</pre >";
}
$texte=preg_replace_callback('#<pre (.*?)>(.*?)</pre >#ius','echapcode',$text);
add_filter('the_content','new_pre_content');
function new_pre_content($content){
	if(function_exists('ampforwp_is_amp_endpoint')&&ampforwp_is_amp_endpoint()){
		$content=preg_replace_callback('#<pre (.*?)>(.*?)</pre >#ius','echapcode',$content);
	}
	return $content;
}
Categories: CMS, PHP Tags: ,
27 октября 2017 Нет комментариев

Актуально для CentOS.
При ошибке PHP Fatal error: Class 'DOMDocument' not found in необходимо установить пакет php-xml

yum install php-xml
apachectl restart
Categories: Linux Tags: ,
4 октября 2017 Нет комментариев

Форматирование телефонов, указанных в произвольном формате.
Например, для преобразования телефона в ссылку tel:

function href_tel($phone,$text=''){
	if(!$text){
		$text=$phone;
	}
	$d=preg_replace('~\D+~','',$phone);
	if(strlen($d)>=10){
		return '<a href="tel:+7'.substr($d,-10,10).'">'.$text.'</a>';
	}
	else{
		return $phone;
	}
}

Преобразование к формату +7 (999) 123-45-67:

function phone_format($phone){
	$d=substr(preg_replace('~\D+~','',$phone),-10,10);
	if(strlen($d)>=10){
		return "+7 (".substr($d,0,3).") ".substr($d,3,3)."-".substr($d,6,2)."-".substr($d,8,2);
	}
	else{
		return $phone;
	}
}
Categories: PHP Tags:
25 сентября 2017 Нет комментариев

Делаем экспорт каталога товаров имея дамп БД от WordPress.
В результате массив, который обрабатываем отталкиваясь от задачи.
Многие данные могут быть специфическими для конкретного проекта.

<?php
//config
$mysql=array(
	'host'=>'localhost',
	'user'=>'db_user',
	'password'=>'db_password',
	'database'=>'db_name',
);
mysql_connect($mysql['host'],$mysql['user'],$mysql['password']) or die ('error mysql_connect');
mysql_select_db($mysql['database']) or die ('error mysql_select_db');
mysql_query("set names 'utf8'");
//database functions
function get_from_base($what,$from,$where='(1)',$order='id'){
	if(trim($what)!=''&&trim($from)!=''&&trim($where)!=''&&trim($order)!=''){
		$arr=array();
		$query="select ".$what." from ".$from." where ".$where." order by ".$order;
		$result=mysql_query($query);
		echo mysql_error();
		if(mysql_num_rows($result)>0){
			while($tmp=mysql_fetch_assoc($result)){
				$arr[]=$tmp;
			}
			return $arr;
		}
	}else{
		return false;
	}
}
function get_one_from_base($what,$from,$where='(1)',$order='id'){
	if(trim($what)!=''&&trim($from)!=''&&trim($where)!=''&&trim($order)!=''){
		$arr=array();
		$query="select ".$what." from ".$from." where ".$where." order by ".$order;
		$result=mysql_query($query);
		echo mysql_error();
		if($result){
			if(mysql_num_rows($result)>0){
				return mysql_fetch_assoc($result);
			}
		}
	}
	return false;
}
//work functions
function make_tree($parent,$parent_chpu=''){
	$tree=array();
	$cats=get_from_base('*','wp_term_taxonomy',"`taxonomy`='product_cat' AND `parent`='".$parent."'",'term_taxonomy_id');
	if(count($cats)>0){
		$cat_chpu=$parent_chpu;
		for($i=0;$i<=count($cats)-1;$i++){
			//$tree[$i]=$cats[$i];
			$tree[$i]=array(
				'wid'=>$cats[$i]['term_id'],
				'description'=>$cats[$i]['description'],
			);
			$term=get_one_from_base('*','wp_terms',"`term_id`='".$cats[$i]['term_id']."'",'term_id');
			if($term['term_id']){
				//$tree[$i]['term']=$term;
				$tree[$i]['name']=$term['name'];
				$tree[$i]['chpu']=urldecode($term['slug']);
				$cat_chpu=$parent_chpu.'/'.urldecode($term['slug']);
			}
			$tree[$i]['link']='/product-category'.$cat_chpu;
			$tree[$i]['childs']=make_tree($cats[$i]['term_taxonomy_id'],$cat_chpu);
			$tree[$i]['items']=get_products($cats[$i]['term_taxonomy_id'],$cat_chpu);
		}
	}
	return $tree;
}
function get_products($parent,$parent_chpu=''){
	$products=array();
	$relationships=get_from_base('*','wp_term_relationships',"`term_taxonomy_id`='".$parent."'",'object_id');
	if(count($relationships)>0){
		foreach($relationships as $i=>$object){
			$product=get_one_from_base('*','wp_posts','`post_type`="product" and `ID`='.$object['object_id'],'ID');
			$product['meta']=get_from_base('*','wp_postmeta','`post_id`="'.$object['object_id'].'"','meta_id');
			//$products[]=$product;
			$products[$i]=array(
				'wid'=>$product['ID'],
				'name'=>$product['post_title'],
				'announce'=>prepare_html($product['post_excerpt']),
				'content'=>prepare_html($product['post_content']),
				'chpu'=>urldecode($product['post_name']),
				'link'=>'/shop'.$parent_chpu.'/'.urldecode($product['post_name']),
				//'meta'=>$product['meta'],
			);
			if(count($product['meta'])>0){
				foreach($product['meta'] as $meta){
					if($meta['meta_value']){
						switch($meta['meta_key']){
							case '_price':
								$products[$i]['price']=$meta['meta_value'];
							break;
							case '_thumbnail_id':
								$photo=get_one_from_base('*','wp_posts','`ID`='.$meta['meta_value'],'ID');
								if($photo['ID']){
									$photo_url=parse_url($photo['guid']);
									$products[$i]['photo']=$photo_url['path'];
								}
							break;
							case '_sku':
								$products[$i]['part']=$meta['meta_value'];
							break;
						}
					}
				}
			}
		}
	}
	return $products;
}
function prepare_html($html){
	$html=str_replace("\r\n\r\n","</p><p>",$html);
	$html=str_replace("\r\n","<br/>",$html);
	return "<p>".$html."</p>";
}
//work
$tree=make_tree(0);
echo '<pre>';print_r($tree);echo '</pre >';
?>
Categories: CMS Tags: ,
18 сентября 2017 Нет комментариев
phpbrew config
phpbrew fpm restart
Categories: Unix Tags:
24 августа 2017 Нет комментариев

Для открытия в браузере:

header("Content-type:application/pdf");
header("Content-Disposition:inline;filename='agreement.pdf'");

Для скачивания:

header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='agreement.pdf'");
Categories: PHP Tags:
8 августа 2017 Нет комментариев

При формировании XML:

$text=preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ',$text);

Полная функция:

function prepare_to_xml($text){
	$text=preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ',$text);
	$text=strip_tags($text);
	$text=htmlspecialchars($text);
	$text=str_replace("\t"," ",$text);
	$text=str_replace("&amp;nbsp;"," ",$text);
	$text=str_replace("&nbsp;"," ",$text);
	$text=preg_replace("/[\r\n]+/i","",$text);
	$text=preg_replace('/ {2,}/',' ',$text);
	$text=trim($text);
	return $text;
}

Ну или просто:

function utf8_for_xml($string){
	return preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',' ',$string);
}
Categories: PHP Tags: ,