skip to Main Content

I want to get <a> element of html. I use xPath /html/body/nav/div/a but not correct. Someone know how I get the Example text ?

<nav class="navbar  navbar-expand-xl" id="menu">
    <div>
<a>
<i class="fas fa-user mr-2"></i>
        Example text
</a>
    </div>

2

Answers


  1. Your code should look like this :

    <i class="fas fa-user mr-2"> Example text </i>
    

    Here is the parse coding:

    <?php
      $doc = new DOMDocument();
      $doc->loadHTML("<html><body><h1>Parsing Html in PHP</h1></body></html>");
      echo $doc->saveHTML();
    ?>
    
       
    
    Login or Signup to reply.
  2. You can parse it via DOM or use XPath.

    Here is an example of each.
    Demo: https://3v4l.org/nvcYP

    $html = <<<'_HTML'
    <nav class="navbar navbar-expand-xl" id="menu">
        <div>
            <a><i class="fas fa-user mr-2"></i>Example text</a>
        </div>
    </nav>
    _HTML;
    
    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    
    // parsing the elements
    $nav = $doc->getElementById('menu');
    $text = $nav->getElementsByTagName('a')->item(0)->nodeValue;
    echo $text;
    
    // using xpath
    $xpath = new DOMXPath($doc);
    $text = $xpath->query('//nav[@id="menu"]/div/a')->item(0)->nodeValue;
    echo $text;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search