php - Get first li Simple DOM Parser

775

I just try to create small simplephpdome
target is

<ul id=filter><li><a href="url1"></li><li><a href="url2"></li></ul>
<ul id=filter><li><a href="url3"></li><li><a href="url4"></li></ul>

How to get just firstli result for everyul?
I have try this

$html = file_get_html($url);
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
$first_list_links = $xpath->evaluate('//ul[@id="filter"]/li/a');

foreach($first_list_links as $links) {
    echo $dom->saveHTML($links);
}

but allli still included

680

Answer

Solution:

You can achieve this using the PHP Simple HTML DOM Parser :

PHP

$html = file_get_html('<ul ><li><a href="url1"></li><li><a href="url2"></li></ul><ul ><li><a href="url3"></li><li><a href="url4"></li></ul>');
$urls = [];
foreach($html->find('.filter') as $element) {
  $url = $element->firstChild()->find('a', 0)->href;
  if (!in_array($url, $urls)) {
    echo $url . "<br/>";
    $urls[] = $url;
  }
}

should output :

url1
url2

People are also looking for solutions to the problem: php - Check if a date has been selected. Bootstrap input type date

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.