使用XPath访问子段落内容

时间:2018-05-19 20:25:55

标签: php xpath

HTML:

<div class="b-list-fact__item-explanation js-fact-explanation">
    <p>Text 1 Text 1 Text 1 Text 1 Text 1 Text 1</p>
    <p>Text 2 Text 2 Text 2 Text 2 Text 2 Text 2 </p>
</div>

我正在尝试访问段落中的文本,并将所有p组合成一个字符串。

尝试了很多变体,例如:

PHP(在7.1.11上运行):

    $html = file_get_contents('https://...');
    $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
    $dom = new DOMDocument;
    @$dom->loadHTML($html);

    $finder = new DomXPath($dom);
    $facts = $finder->query("//a[contains(@class, normalize-space('b-list-fact__item-text'))]");
    $long_fact = $finder->query("//*[contains(@class, 'b-list-fact__item-explanation js-fact-explanation')]/p");

    foreach ($facts as $key => $fact) {
            $fact_description = $long_fact[$key]->textContent;
            $fact = trim($fact->textContent);
            $dataArr[] = str_replace("\n", " ", $fact);
            array_push($dataArr, $fact_description);
    }

$long_fact = $finder->query("//*[contains(@class, 'b-list-fact__item-explanation js-fact-explanation')]/p");

$long_fact = $finder->query("//*[contains(@class, 'b-list-fact__item-explanation js-fact-explanation')]//p[1]");

$long_fact = $finder->query("//*[contains(@class, 'b-list-fact__item-explanation js-fact-explanation')]/p/text()");

if($long_fact->length)
        {
            var_dump($long_fact[0]->textContent);
        }

if($$long_fact->length)
        {
            var_dump($long_fact->textContent);
        }

if($$long_fact->length)
        {
            var_dump($long_fact->nodeValue);
        }

和其他30个变种一样......

我完全不知道为什么会发生这种情况,其他不包含p代码的变体工作正常。

1 个答案:

答案 0 :(得分:1)

$ptext = $finder->query('//div[contains(@class, "b-list-fact__item-explanation js-fact-explanation")]/p');
$paragraphs = [];
foreach ($ptext as $paragraph) {
    $paragraphs[] = $paragraph->textContent;
}
$combined = implode("\n", $paragraphs);

或者只是:

$ptext = $finder->query('//div[contains(@class, "b-list-fact__item-explanation js-fact-explanation")]')
    ->item(0)->textContent;