Приятные мелочи на php

Пишу эту заметку для себя, вдруг мне пригодиться, в моем компьютере потеряется, а тут на блоге останется навсегда — да и Вам может пригодиться ;-).
Две маленькие функции на php:
- Определение Тематического Индекса Цитирования
- Многоязычный переводчик
Определение ТИЦ
Берет значения тИЦ напрямую из Яндекс.Каталога, очень быстрая скорость работы. Писал не Я, писал .
<?php
function yandex_tic($url){
$file=file_get_contents("http://search.yaca.yandex.ru/yca/cy/ch/$url/");
if(preg_match("!—\s+([0-9]{0,8})<\/b>!is",$file,$ok)){
// сайт не в каталоге.
$str=$ok[1];
}
else if(preg_match("!<td class=\"current\" valign=\"middle\">(.*?)</td>\n</tr>!si", $file, $ok)){
if(preg_match("!<td align=\"right\">(.*?)</td>\n</tr>!si", $ok[0], $str)){
// сайт в каталоге.
$str=$str[1];
} else {
$str=0;
}
}
else {
$str=0;
}
return trim($str);
}
// Пример:
// echo yandex_tic("zhilinsky.ru")
?>
Многоязычный переводчик
Работает через .
Работает быстро. Писал Я, на коленке, поэтому криво, если будут замечания — пишите! Я исправлюсь ;-)
<?php
function translate($text,$lg) {
$lg = urlencode($lg);
$text = urlencode($text);
$link = file_get_contents("http://google.com/translate_t?langpair=$lg&text=$text");
preg_match('/<div id=result_box dir=\"ltr\">(.*?)<\/div>/', $link, $out);
return $out[1];
}
// Пример:
// echo translate("hello")
// Пример c другим языком(С Английского на Немецкий):
// echo translate("hello", "en|de")
?>

Вполне неплохо, но пригодится только для маленьких заданий. Иначе забанят негодяи :) Попомучался я пару дней с переводом городов мира при помощи этого транслятора. Даже прокси не каждые помогали. Еще и сейчас товарищ мучается, продолжает. И как оказалось, для транслятора недавно открыли доступный API :)
А про тиц еще вот хорошая заметка.
http://kurilka.co.ua/archives/alternative-variants-receipt-cy – на основе распознавания текста с картинки. Хотя, уверен, Вы с ней (заметкой) знакомы :)
Днями просиживаю штаны в интернете, а про переводчик от гугля первый раз слышу… чудеса :-O
Они только недавно открыли свое API по переводчику.
А как сервис гугля переводчик живет уже оооочень давно
file_get_contents(«http://…»):
Это ужас, никогда так не пишите! ТОЛЬКО с помощью сокетов или cURL.
Ну гореть мне в пхп аду :-). А чем плох этот метод? Работает ведь!
Этот метод работает но не везде и не во всех ситуациях. И вот несколько причин подтверждающих это:
1. file_get_contents работает только с удаленными хостами толдько при включенной директиве allow_url_fopen в php.ini (установить эту директиву в .htaccess или скрипте нельзя). Как правило хостеры ее отключают. По крайней мере умные.
2. file_get_contents не имеет параметра тайм-аута, что самое важное,т.к. в случае если сайт не отвечает или тяжело отвечает, скрипт может легко «подвиснуть».
3. Если где-то используется file_get_contents и случайно пропущена обработка возможности ошибочного входного параметра, то может быть XSS или переполнения буфера.
4. Нет возможности указать порт, по которому необходимо соединиться с сервером.
$ctx = stream_context_create(array(http://…' , 0, $ctx);
‘http’ => array(
‘timeout’ => 60
)
)
);
$img = @file_get_contents(‘
To: Strike
Все там есть и порт и прокси даже указать можно, если ничего не знаешь – зачем писать про эту функцию.
Вот тебе еще
// Define a context for HTTP.
$aContext = array(
‘http’ => array(
‘proxy’ => ‘tcp://127.0.0.1:8080′, // This needs to be the server and the port of the NTLM Authentication Proxy Server.
‘request_fulluri’ => True,
),
);
$cxContext = stream_context_create($aContext);
// Now all file stream functions can use this context.
$sFile = file_get_contents(«http://…», False, $cxContext);
echo $sFile;
а вот русский не хавает :(
по примеру переводчика хотел сделать парсер текстов песен! но что то не работает, может кто поможет? мне кажеться очень полезно было бы. вот код:
<?php
function text($artist,$title) {
$title = urlencode($title);
$artist = urlencode($artist);
$link = file_get_contents(«http://www.lyricsplugin.com/wmplayer03/plugin/?artist=$artist&title=$title»);
preg_match(‘/(.*?)/’, $link, $out);
return $out[1];
}
//http://www.lyricsplugin.com/wmplayer03/plugin/?artist=Каста&title=Ревность
echo text(«Каста», «Ревность»)
?>
Айпи постоянно банится.
Fantastic submit admin! i bookmarked your word wide web blog. i’ll search ahead should you will have an e-mail record including.
Greetings thanks for wonderful submit i used to be browsing for this issue survive a couple of days and nights. I’ll look for following precious posts. Have fun admin.
I was curious about your future article admin definitely essential this blog site super wonderful weblog
I was searching for this blog site survive three or more days wonderful webpage owner great posts every thing is superb
Terrific submit admin thank you. I found what i was trying to find here. I will review entire of posts in this time of day
Great article admin thank you. I discovered what i was trying to find here. I’ll review whole of posts in this evening
Genuinely required post admin fantastic one particular i bookmarked your website webpage see you in upcoming blog site put up.
Great 1 weblog manager achievements blog site put up great sharings with this web site always have enjoyable
hey admin thanks for good and straightforward understandable put up i liked your blog site website definitely much bookmarked also
Genuinely needed article admin good a person i bookmarked your web sheet see you in subsequent website post.
Nice a person webpage operator results weblog post great sharings in this weblog usually have fun
Fantastic post admin! i bookmarked your net webpage. i will look ahead should you could have an e-mail record including.
I was curious about your subsequent post admin seriously necessary this webpage super amazing webpage
you’re seriously range 1 admin your blogging is astounding i at all times verify your website i’m certain you will be the best
Greetings thanks for fantastic post i used to be browsing for this issue last a couple of days. I’ll look for subsequent precious posts. Have enjoyable admin.
Great article admin thank you. I identified what i used to be searching for right here. I’ll review whole of posts within this working day
you happen to be actually quantity a person admin your blogging is remarkable i always test your webpage i am positive you will probably be the very best
Really required post admin excellent 1 i bookmarked your net page see you in subsequent weblog publish.
Hello admin excellent put up much thanks cherished this website actually very much
i bookmarked you in my browser admin thank you so much i might be in search of your up coming posts
i bookmarked you in my browser admin thank you so much i is going to be trying to find your future posts
ПриÑтные мелочи на php | Чернев.ру I was suggested this web site by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my problem. You’re wonderful! Thanks! your article about ПриÑтные мелочи на php | Чернев.руBest Regards Lawrence
Genuinely needed put up admin wonderful a single i bookmarked your web webpage see you in next blog site article.
I needed for this web site submit admin actually thanks i will seem your next sharings i bookmarked your website
i cant get how you are able to reveal like this wonderful posts admin very much thanks
hey admin thanks for fantastic and easy understandable article i liked your blog website really considerably bookmarked also
ПриÑтные мелочи на php | Чернев.ру I was suggested this blog by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my problem. You are incredible! Thanks! your article about ПриÑтные мелочи на php | Чернев.руBest Regards SchaadAndy
Wow, awesome blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is excellent, let alone the content!. Thanks For Your article about ПриÑтные мелочи на php | Чернев.ру .
This is the accurate ПриÑтные мелочи на php | Чернев.ру journal for anyone who wants to assay out out near this subject. You note so such its nearly debilitating to converse with you (not that I really would want…HaHa). You definitely put a new extend on a message thats been handwritten about for period. Squeamish sundry, simply majuscule!
OK, to talk about something else, for KG, the latest update about the NPD, the only remaining Nazi party in Germany of note:
Chili for 35.
I can do that.
I was seeking for this great sharing admin a lot thanks and have great running a blog bye
Wonderful article admin! i bookmarked your website blog site. i will seem ahead when you can have an e-mail list including.
hey admin thanks for good and effortless understandable publish i liked your website internet site definitely much bookmarked also
I’m not sure where you’re getting your info, but great topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic information I was looking for this ПриÑтные мелочи на php | Чернев.ру for my mission.
ПриÑтные мелочи на php | Чернев.ру I was suggested this web site by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my problem. You’re wonderful! Thanks! your article about ПриÑтные мелочи на php | Чернев.руBest Regards Rolf
I got what you will, thanks for putting up. Woh I am glad to learn this website through google. Thanks For Share ПриÑтные мелочи на php | Чернев.ру.
Wow, awesome blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is great, let alone the content!. Thanks For Your article about ПриÑтные мелочи на php | Чернев.ру .
Hey There. I found your blog using msn. This is a very well written article. I will make sure to bookmark it and return to read more of ПриÑтные мелочи на php | Чернев.ру . Thanks for the post. I’ll certainly return.
An intriguing discourse is couturier observe. I believe that you should indite solon on this substance, it might not be a inhibition somebody but mostly people are not sufficiency to verbalise on much topics. To the succeeding. Cheers like your ПриÑтные мелочи на php | Чернев.ру.