[英]How can i get the text from a child node with php DOMDocument
我一直在編寫 php 代碼來從站點獲取信息,到目前為止我能夠獲取 href 屬性,但是我找不到從子節點“span”獲取文本的方法,有人可以幫助我嗎?
html->
<a class="js-publication" href="publication/247931167">
<span class="publication-title">An approach for textual authoring</span>
</a>
這就是我目前能夠獲得 href ->
@$dom->loadHTMLFile($curPage);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $element) {
$class_ = $element->getAttribute('class');
if (0 !== strpos($class_, 'js-publication')) {
$href = $element->getAttribute('href');
if(0 === stripos($href,'publication/')){
echo $href;//link para a publicação;
echo "\n";
}
}
}
您可以使用DOMXpath
$html = <<< LOL
<a class="js-publication" href="publication/247931167">
<span class="publication-title">An approach for textual authoring</span>
</a>
LOL;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
foreach ($xpath->query("//a[@class='js-publication']") as $element){
echo $element->getAttribute('href');
echo $element->textContent;
}
//publication/247931167
//An approach for textual authoring
或者沒有for
循環,如果你只想要一個元素:
echo $xpath->query("//a[@class='js-publication']/span")[0]->textContent;
echo $xpath->query("//a[@class='js-publication']")[0]->getAttribute('href');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.