simple html domで情報を取得・WPに保存
simple html domを使用して指定サイトから、情報を取得する必要があったのでメモ。
設定の方法等については、PHP Simple HTML DOM Parserをご確認ください。
取得の仕方
必要なファイルを、アップし読み込みます。
情報を取得したいURLを記述して、
取得したいタグを指定すれば完了です。
$get_dir_path = dirname(__FILE__); $pass = $get_dir_path.'/simple_html_dom.php'; require_once $pass; $html = file_get_html('URLを記載'); $find_title = $html_sub->find('取得したいタグ'); foreach($find_title as $e){ $t = $e->plaintext; //テキストで取得 $title = array($t); } var_dump($title); // タイトル情報を取得
WP上で取得した情報を保存
情報を取得し、投稿上にデータを保存します。
もし、情報が既に存在しない場合は削除するようにしました。
/********** 情報取得 ***********/ $find_a = $html->find('取得したいhtmlを指定'); //urlからid取得 foreach($find_a as $e){ $url = $e->href; //URLからIDを取得 $num = preg_replace('/[^0-9]/', '', $url); $url_array[] = array('id'=>$num,'url'=>$url); } /********** 投稿IDを取得 **********/ $args = array( 'posts_per_page' => -1, 'post_type' => 'post', 'post_status' => 'publish', ); $posts_array = get_posts( $args ); $post_ID = array(); //投稿ID抽出 foreach ($posts_array as $post ) { setup_postdata( $post ); $post_ID[] = $post->post_name; } wp_reset_postdata(); $post_ID_data = $post_ID; /***** 取得サイトに既に情報がなければ 自サイトの投稿を削除 *****/ foreach($post_ID_data as $v){ $post_chk = in_array( $v , array_column( $url_array, 'id')); $args = array( 'post_type' => 'POST', 'name' => $v); $posts = get_posts( $args ); if($post_chk === false ){ if ( $posts ) { $id = $posts[0]->ID; $dele_post = array( 'ID' => $id, // ID 'post_name' => $v, // name 'post_status' => 'trash', 'post_type' => 'post', ); wp_update_post( $dele_post ); } } } /***** 投稿情報の取得 *****/ $custonm_field = array(); foreach($url_array as $val){ $id = $val['id']; $url = $val['url']; $post_ID_result = in_array($id, $post_ID_data, true); $custonm_field['id'] = $id; //新規投稿 if($post_ID_result === false ){ $html_sub = file_get_html($url); //タイトル $title = array(); $find_title = $html_sub->find('取得したいタグ'); foreach($find_title as $e){ $t = $e->plaintext; $title = array($t); } //本文 $html = ''; $find_copy = $html_sub->find('取得したいタグ'); foreach($find_copy as $e){ $html .= $e->innertext; } $find_txt = $html_sub->find('取得したいタグ'); //募集情報 if(!empty($find_txt)){ $txt = ''; foreach($find_txt as $e){ $txt = $e->outertext; $custonm_field['job_info'] = $txt; } } /*** 投稿設定 ***/ //投稿 $posts = array( 'post_content' => $html, // 全文 'post_name' => $id ,//スラッグ 'post_title' => $title[0], //タイトル 'post_status' => 'publish', 'post_type' => 'post', 'post_author' => 'ユーザー' // 作成者のユーザー ); $post_new_id = wp_insert_post( $posts ); //投稿を追加してIDを発行 //カスタムフィールド の値 update_field('info',$custonm_field['info'], $post_new_id); } else { //それ以外の処理 } } $html->clear(); //クリア