繁体   English   中英

php DomXPath-如何从nodeValue剥离html标签及其内容?

[英]php DomXPath - how to strip html tags and its contents from nodeValue?

在这段代码中

<root>
    <main>
        <cont>
            <p>hello<a>world</a></p>
            <p>hello</p>
            <p>hello<a>world</a></p>
        </cont>
    </main>
</root>

我只需要在<cont>标记内获取文本。 没有获取<a>标签its contents

因此,结果将是hello hello hello没有world

一个simplexml_load_string()simplexml_load_file()应该足够:

$xml_string = '<root> <main> <cont> <p>hello<a>world</a></p> <p>hello</p> <p>hello<a>world</a></p> </cont> </main></root>';
$xml = simplexml_load_string($xml_string);
$p = $xml->main->cont->p;
foreach($p as $value) {
    $parapgraphs[] = (string) $value;
}

echo '<pre>';
print_r($parapgraphs);

应该显示如下内容:

Array
(
    [0] => hello
    [1] => hello
    [2] => hello
)

您可以选择作为每个<p>标记的直接后代的文本节点:

$dom = new DOMDocument;
$dom->loadXml($xmlData);

$xpath = new DOMXpath($dom);

foreach ($xpath->query('//cont/p/text()') as $text) {
    echo $text->textContent, "\n";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM