wordpress
指定のページの指定のclass内を別のサイトのページに取り込むPHPコードVer3
作成日: 2025年3月20日
今回は
function.php記述
ショートコードで投稿に挿入
一応1ページから3か所のスクレイピング可能
PHPのバージョンによりエラー発生の可能性あり(php 8.2upはOK)
※ブランドサイトなども扱う際、各サイト共通項の一元管理用
<?php
// ショートコードでスクレイピング処理を実行する関数
function scrape_child_pages_shortcode() {
// スクレイピング対象のURL(具体的なパスを記述)
$url = "https://example.com"; // ここに実際のURLを記述(例:https://example.com)
// HTMLを取得
$context = stream_context_create([
'http' => [
'timeout' => 10,
'header' => "User-Agent: PHP\r\n",
]
]);
$html = @file_get_contents($url, false, $context);
if ($html === false) {
$error = error_get_last();
return '<p>Failed to fetch content from the URL: ' . htmlspecialchars($error['message'] ?? 'Unknown error', ENT_QUOTES, 'UTF-8') . '</p>';
}
// エンコーディングの検出と変換
$encoding = mb_detect_encoding($html, 'UTF-8, Shift_JIS, EUC-JP', true);
if ($encoding && $encoding !== 'UTF-8') {
$html = mb_convert_encoding($html, 'UTF-8', $encoding);
}
// DOMDocumentでHTMLをパース
libxml_use_internal_errors(true); // パースエラーを無視
$dom = new DOMDocument();
@$dom->loadHTML('<?xml encoding="UTF-8">' . $html); // UTF-8を明示
libxml_clear_errors();
// DOMXPathで特定のクラスを持つ要素を取得(順序指定)
$xpath = new DOMXPath($dom);
// 出力を格納する変数
$output = '';
// 最初のクラス
$firstNode = $xpath->query("(//div[contains(@class, 'child_pages')])[1]"); // 1つ目の要素 div→section child_page→任意のクラス @class→@id可
if ($firstNode->length > 0) {
$output .= $dom->saveHTML($firstNode->item(0)) . "\n\n";
}
// 2つ目のクラス
$secondNode = $xpath->query("(//div[contains(@class, 'child_pages')])[2]"); // 2つ目の要素
if ($secondNode->length > 0) {
$output .= $dom->saveHTML($secondNode->item(0)) . "\n\n";
}
// 3つ目のクラス
$thirdNode = $xpath->query("(//div[contains(@class, 'child_pages')])[3]"); // 3つ目の要素
if ($thirdNode->length > 0) {
$output .= $dom->saveHTML($thirdNode->item(0)) . "\n\n";
}
// 要素が見つからなかった場合
if ($firstNode->length === 0 && $secondNode->length === 0 && $thirdNode->length === 0) {
$output .= "指定されたクラス(child_pages)を持つ要素が見つかりませんでした。\n";
}
return $output;
}
// ショートコードを登録
add_shortcode('scrape_child_pages', 'scrape_child_pages_shortcode');
?>