14 апреля 2008 ~ 4764 Комментария

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

php

PHP-logo-140_74px

Пишу эту заметку для себя, вдруг мне пригодиться, в моем компьютере потеряется, а тут на блоге останется навсегда — да и Вам может пригодиться ;-).

Две маленькие функции на 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")
?>

Многоязычный переводчик

Работает через Google Переводчик.

Работает быстро. Писал Я, на коленке, поэтому криво, если будут замечания — пишите! Я исправлюсь ;-)

<?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")
?>

4764 Комментария для “Приятные мелочи на php”

  1. EwGenij 15 апреля 2008 at 0:03 Permalink

    Вполне неплохо, но пригодится только для маленьких заданий. Иначе забанят негодяи :) Попомучался я пару дней с переводом городов мира при помощи этого транслятора. Даже прокси не каждые помогали. Еще и сейчас товарищ мучается, продолжает. И как оказалось, для транслятора недавно открыли доступный API :)

    А про тиц еще вот хорошая заметка.
    http://kurilka.co.ua/archives/alternative-variants-receipt-cy – на основе распознавания текста с картинки. Хотя, уверен, Вы с ней (заметкой) знакомы :)

  2. Александр 15 апреля 2008 at 0:39 Permalink

    Днями просиживаю штаны в интернете, а про переводчик от гугля первый раз слышу… чудеса :-O

  3. Zeldar 15 апреля 2008 at 2:00 Permalink

    Они только недавно открыли свое API по переводчику.
    А как сервис гугля переводчик живет уже оооочень давно

  4. AztEK 15 апреля 2008 at 17:22 Permalink

    file_get_contents(«http://…»):

    Это ужас, никогда так не пишите! ТОЛЬКО с помощью сокетов или cURL.

  5. Я собственной персоной 15 апреля 2008 at 18:38 Permalink

    file_get_contents(«http://…»):

    Это ужас, никогда так не пишите! ТОЛЬКО с помощью сокетов или cURL.

    Ну гореть мне в пхп аду :-). А чем плох этот метод? Работает ведь!

  6. Strike 16 июля 2008 at 4:20 Permalink

    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. Нет возможности указать порт, по которому необходимо соединиться с сервером.

  7. aleksej 2 августа 2008 at 0:43 Permalink

    $ctx = stream_context_create(array(
    ‘http’ => array(
    ‘timeout’ => 60
    )
    )
    );
    $img = @file_get_contents(‘http://…', 0, $ctx);

    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;

  8. test 17 октября 2008 at 20:24 Permalink

    а вот русский не хавает :(

  9. Алексей 20 октября 2008 at 2:35 Permalink

    по примеру переводчика хотел сделать парсер текстов песен! но что то не работает, может кто поможет? мне кажеться очень полезно было бы. вот код:

    <?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(«Каста», «Ревность»)

    ?>

  10. Металлоконструкции 2 марта 2010 at 17:55 Permalink

    Айпи постоянно банится.

  11. doğum kontrol yöntemleri 3 февраля 2012 at 10:44 Permalink

    Fantastic submit admin! i bookmarked your word wide web blog. i’ll search ahead should you will have an e-mail record including.

  12. Network Rehberi 3 февраля 2012 at 11:59 Permalink

    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.

  13. güncel blog 4 февраля 2012 at 2:00 Permalink

    I was curious about your future article admin definitely essential this blog site super wonderful weblog

  14. dizi izle 4 февраля 2012 at 3:10 Permalink

    I was searching for this blog site survive three or more days wonderful webpage owner great posts every thing is superb

  15. lüks araç kiralama 4 февраля 2012 at 8:34 Permalink

    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

  16. yarış oyunu 4 февраля 2012 at 13:50 Permalink

    Great article admin thank you. I discovered what i was trying to find here. I’ll review whole of posts in this evening

  17. chat 4 февраля 2012 at 16:18 Permalink

    Genuinely required post admin fantastic one particular i bookmarked your website webpage see you in upcoming blog site put up.

  18. liseli porno 4 февраля 2012 at 17:58 Permalink

    Great 1 weblog manager achievements blog site put up great sharings with this web site always have enjoyable

  19. köpek eğitimi 5 февраля 2012 at 9:03 Permalink

    hey admin thanks for good and straightforward understandable put up i liked your blog site website definitely much bookmarked also

  20. şarkı sözü 5 февраля 2012 at 10:11 Permalink

    Genuinely needed article admin good a person i bookmarked your web sheet see you in subsequent website post.

  21. porno 6 февраля 2012 at 10:44 Permalink

    Nice a person webpage operator results weblog post great sharings in this weblog usually have fun

  22. bayan escort 6 февраля 2012 at 15:44 Permalink

    Fantastic post admin! i bookmarked your net webpage. i will look ahead should you could have an e-mail record including.

  23. panax 7 февраля 2012 at 14:29 Permalink

    I was curious about your subsequent post admin seriously necessary this webpage super amazing webpage

  24. şifreli kapı kilidi 8 февраля 2012 at 13:36 Permalink

    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

  25. escort bayan istanbul 10 февраля 2012 at 3:16 Permalink

    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.

  26. windows hosting 10 февраля 2012 at 6:48 Permalink

    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

  27. Biyografi 10 февраля 2012 at 8:22 Permalink

    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

  28. mimari fotoğraf 12 февраля 2012 at 0:19 Permalink

    Really required post admin excellent 1 i bookmarked your net page see you in subsequent weblog publish.

  29. ayakkabı modelleri 12 февраля 2012 at 3:23 Permalink

    Hello admin excellent put up much thanks cherished this website actually very much

  30. medyum hoca 12 февраля 2012 at 4:44 Permalink

    i bookmarked you in my browser admin thank you so much i might be in search of your up coming posts

  31. web tasarım 13 февраля 2012 at 20:58 Permalink

    i bookmarked you in my browser admin thank you so much i is going to be trying to find your future posts

  32. invest liberty reserve 16 февраля 2012 at 2:20 Permalink

    Приятные мелочи на 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

  33. şarkı sözü 16 февраля 2012 at 8:58 Permalink

    Genuinely needed put up admin wonderful a single i bookmarked your web webpage see you in next blog site article.

  34. msn aç 16 февраля 2012 at 9:29 Permalink

    I needed for this web site submit admin actually thanks i will seem your next sharings i bookmarked your website

  35. lenovo şarj aleti 16 февраля 2012 at 11:55 Permalink

    i cant get how you are able to reveal like this wonderful posts admin very much thanks

  36. Burçlar 16 февраля 2012 at 13:17 Permalink

    hey admin thanks for fantastic and easy understandable article i liked your blog website really considerably bookmarked also

  37. invest liberty reserve 16 февраля 2012 at 19:20 Permalink

    Приятные мелочи на 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

  38. invest liberty reserve 16 февраля 2012 at 21:20 Permalink

    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 | Ð§ÐµÑ€Ð½ÐµÐ².ру .

  39. invest liberty reserve 16 февраля 2012 at 23:03 Permalink

    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!

  40. medula eczane 17 февраля 2012 at 6:42 Permalink

    OK, to talk about something else, for KG, the latest update about the NPD, the only remaining Nazi party in Germany of note:

  41. dünyanın 7 harikası 17 февраля 2012 at 7:32 Permalink

    Chili for 35.
    I can do that.

  42. tek parça film 17 февраля 2012 at 12:29 Permalink

    I was seeking for this great sharing admin a lot thanks and have great running a blog bye

  43. Kanser bitkisel tedavisi 17 февраля 2012 at 14:46 Permalink

    Wonderful article admin! i bookmarked your website blog site. i will seem ahead when you can have an e-mail list including.

  44. muhabbet kuşu 17 февраля 2012 at 15:18 Permalink

    hey admin thanks for good and effortless understandable publish i liked your website internet site definitely much bookmarked also

  45. invest liberty reserve 17 февраля 2012 at 21:16 Permalink

    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.

  46. quotes on lost love 18 февраля 2012 at 19:51 Permalink

    Приятные мелочи на 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

  47. quotes on lost love 18 февраля 2012 at 20:25 Permalink

    I got what you will, thanks for putting up. Woh I am glad to learn this website through google. Thanks For Share Приятные мелочи на php | Ð§ÐµÑ€Ð½ÐµÐ².ру.

  48. quotes on lost love 18 февраля 2012 at 20:59 Permalink

    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 | Ð§ÐµÑ€Ð½ÐµÐ².ру .

  49. quotes on lost love 18 февраля 2012 at 21:30 Permalink

    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.

  50. Best Android widgets 19 февраля 2012 at 18:53 Permalink

    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 | Ð§ÐµÑ€Ð½ÐµÐ².ру.


Оставить комментарий