Created
December 13, 2017 03:45
-
-
Save bom-shibuya/c69dcd1668b508c66737532547f4d80e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| header("Content-Type: application/json; charset=utf-8"); | |
| class Ogp_getter { | |
| private $url = null; | |
| function __construct($url_strings) { | |
| $this->url = $url_strings; | |
| } | |
| protected function get_html($url) { | |
| // start cURL !!! | |
| $ch = curl_init(); | |
| curl_setopt($ch, CURLOPT_URL, $url); | |
| curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
| $html = curl_exec($ch); | |
| curl_close($ch); | |
| return $html; | |
| } | |
| protected function get_ogp_data($html_source) { | |
| // extract ogp | |
| preg_match_all( | |
| "|<meta property=[\"']og:([^\"']+)[\"'] content=[\"']([^\"']+)[\"'].*?>|", | |
| $html_source, | |
| $extract_result | |
| ); | |
| // easily hunadle data | |
| $i = 0; | |
| $format_result = null; | |
| if (isset($extract_result)) { | |
| foreach($extract_result[1] as $key => $value) { | |
| $format_result[$value] = $extract_result[2][$i]; | |
| $i++; | |
| } | |
| } | |
| return $format_result; | |
| } | |
| protected function get_meta_data($html_source) { | |
| preg_match( | |
| "|<meta name=\"description\" content=[\"']([^\"']+)[\"'].*?>|", | |
| $html_source, | |
| $description | |
| ); | |
| preg_match( | |
| "|<title>(.+?)</title>|", | |
| $html_source, | |
| $title | |
| ); | |
| return array( | |
| 'title' => isset($title[1]) ? $title[1] : null, | |
| 'description' => isset($description[1]) ? $description[1] : null, | |
| ); | |
| } | |
| protected function merge_data($ogp_data, $meta_data, $error_msg = false) { | |
| return array( | |
| 'ogp' => $ogp_data, | |
| 'meta' => $ogp_data, | |
| 'error' => $error_msg, | |
| ); | |
| } | |
| public function run() { | |
| $html = $this->get_html($this->url); | |
| try { | |
| if($html) { | |
| $ogp = $this->get_ogp_data($html); | |
| $meta = $this->get_meta_data($html); | |
| return $this->merge_data($ogp, $meta); | |
| } else { | |
| throw new Exception('can\'t catch content!!'); | |
| } | |
| } catch (Exception $e) { | |
| return $this->merge_data(null, null, $e->getMessage()); | |
| } | |
| } | |
| } | |
| $data = new Ogp_getter($_GET['url']); | |
| echo json_encode($data->run()); | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment