Web scraping in PHP

后端 未结 5 904
梦毁少年i
梦毁少年i 2020-11-27 14:48

I\'m looking for a way to make a small preview of another page from a URL given by the user in PHP.

I\'d like to retrieve only the title of the page, an image (like

5条回答
  •  被撕碎了的回忆
    2020-11-27 15:06

    I recommend you consider simple_html_dom for this. It will make it very easy.

    Here is a working example of how to pull the title, and first image.

    find('title', 0);
    $image = $html->find('img', 0);
    
    echo $title->plaintext."
    \n"; echo $image->src; ?>

    Here is a second example that will do the same without an external library. I should note that using regex on HTML is NOT a good idea.

    ([^<]+)<\/title>/i', $data, $matches);
    $title = $matches[1];
    
    preg_match('/]*src=[\'"]([^\'"]+)[\'"][^>]*>/i', $data, $matches);
    $img = $matches[1];
    
    echo $title."
    \n"; echo $img; ?>

提交回复
热议问题