First Title

...">

Php - get link value

I use php to get part of the html file:

HTML file:

<div class="titles">
    <h2><a href="#">First Title</a></h2>
</div>

PHP file:

<?php
    include_once('simple_html_dom.php');
    $url = 'http://example.com';
    $html = file_get_html($url);
    $titles = $html->find('.titles');
    $heading = $titles->find('h2')[0];
    $link = $heading->find('a')[0];
    echo $link; 
    //result: <a href="#">First Title</a>
?>

How can I separately get the value of the href and 'a' tags?

Since I want to save the title and link to the database,

I need '#' and 'First Title' not a 'a' tag.

+4
source share
2 answers

$linkshould be a simple element of an HTML element that can be accessed using $link->hrefand text content as $link->plaintext. See http://simplehtmldom.sourceforge.net/manual.htm .

+6
source

U can use DOMDocument and DOMXpath object (> = php5)

ref: http://php.net/manual/en/class.domdocument.php

:

$html = '<div class="titles">
<h2><a href="#">First Title</a></h2>
</div>';


$page = new DOMDocument();
$page->loadHtml($html);

$xpath = new DOMXpath($page);
$a = $xpath->query("//a");

for ($i=0; $i < $a->length; $i++) {
    $_a = $a->item($i);

    echo  $_a->getAttribute("href");
    echo "<br>";
    echo  $_a->textContent;


}
0

Source: https://habr.com/ru/post/1625468/


All Articles