LoginSignup
10
8

More than 5 years have passed since last update.

「AからBまでの間に存在する全ての兄弟ノード」をXPathで表現する

Posted at

書式

AからBまでの間に存在する全ての兄弟ノード
A/following-sibling::*[following::B]

使用例

前提知識: 「PHPネイティブのDOMによるスクレイピング入門」

<?php

$html = <<<'EOD'
<!DOCTYPE html>
<title>淫夢要素はありません</title>
<h1>野獣</h1>
<p>イ ン テ ル 長 友</p>
<p>北 島 康 介</p>
<p>鈴 木 福</p>
<h1>遠野</h1>
<p>レ シ ー ト リ ザ ー ド</p>
<p>世界のトオノ</p>
<h1>MUR</h1>
<p>ベ ッ キ ー</p>
<p>ポッチャマ…</p>
<p>池沼</p>
<p>智将</p>
EOD;

$dom = new \DOMDocument;
@$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$xpath = new \DOMXPath($dom);

$stringify = function ($node) {
    return $node->nodeValue;
};
$execute = function ($query) use ($xpath, $stringify) {
    return array_map($stringify, iterator_to_array($xpath->query($query), false));
};
$results = array_map($execute, [
    '野獣' => '//h1[.="野獣"]/following-sibling::p[following::h1[.="遠野"]]',
    '遠野' => '//h1[.="遠野"]/following-sibling::p[following::h1[.="MUR"]]',
    'MUR' => '//h1[.="MUR"]/following-sibling::p',
]);

var_dump($results);

/*
array(3) {
  ["野獣"]=>
  array(3) {
    [0]=>
    string(33) "イ ン テ ル 長 友"
    [1]=>
    string(21) "北 島 康 介"
    [2]=>
    string(15) "鈴 木 福"
  }
  ["遠野"]=>
  array(2) {
    [0]=>
    string(45) "レ シ ー ト リ ザ ー ド"
    [1]=>
    string(18) "世界のトオノ"
  }
  ["MUR"]=>
  array(4) {
    [0]=>
    string(21) "ベ ッ キ ー"
    [1]=>
    string(18) "ポッチャマ…"
    [2]=>
    string(6) "池沼"
    [3]=>
    string(6) "智将"
  }
}
*/
10
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8