phpdomdomready

How to get links in each block PHP DomReady?


I have the following HTML DOM:

<div class="m">
<div class="cr"><a class="link" href="1">1</a><div class="title">1</div></div>
<div class="cr"><a class="link" href="2">2</a><div class="title">2</div></div>
<div class="cr"><a class="link" href="3">3</a><div class="title">3</div></div>
</div>

I need to get in one loop values: .title and href of links.

I tried:

$similar = $xpath->query('//div[@class = "cr"]');

foreach ($similar as $key => $item) {
    $href = ?
    $title = ?
}

Solution

  • You could use the SimpleXMLElement Class for that as demonstrated by the Snippet below which, you may Quick-Test Here.

    <?php
    
        $html = '<div class="m">
                <div class="cr"><a href="1">1</a><div class="title">1st Node Value</div></div>
                <div class="cr"><a href="2">2</a><div class="title">2nd Node Value</div></div>
                <div class="cr"><a href="3">3</a><div class="title">3rd Node Value</div></div>
                </div>';
    
    
        $sXML       = new SimpleXMLElement($html);
        $links      = $sXML->xpath("child::div/a");
        $titles     = $sXML->xpath("child::div/div");
    
        $arrLinks   = array();
        $arrTitles  = array();
    
        foreach($links as $link){
            $arrLinks[]     = (string)$link->xpath("attribute::href")[0];
        }
    
        foreach($titles as $title){
            $arrTitles[]    = (string)$title;
        }
    
        var_dump($arrLinks);        
        // YIELDS::
        array (size=3)
          0 => string '1' (length=1)
          1 => string '2' (length=1)
          2 => string '3' (length=1)
    
        var_dump($arrTitles);
        // YIELDS::
        array (size=3)
          0 => string '1st Node Value' (length=14)
          1 => string '2nd Node Value' (length=14)
          2 => string '3rd Node Value' (length=14)