2016-05-12 8 views
-1

Ich habe einen PHP-Code geschrieben, um Informationen von einer Website zu bekommen, bis jetzt konnte ich das href-Attribut, aber ich kann keinen Weg zu bekommen der Text vom Kindknoten "span", kann mir jemand helfen?Wie bekomme ich den Text von einem Kind-Knoten mit PHP DOMDocument

html->

<a class="js-publication" href="publication/247931167"> 
    <span class="publication-title">An approach for textual authoring</span> 
</a> 

Dies ist, wie ich derzeit in der Lage bin, die href zu bekommen ->

@$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"; 
      } 
     } 
    } 

Antwort

1

Sie 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 

oder ohne for Schleife verwenden können , wenn Sie nur ein Element wünschen:

echo $xpath->query("//a[@class='js-publication']/span")[0]->textContent; 
echo $xpath->query("//a[@class='js-publication']")[0]->getAttribute('href'); 

Ideone Demo