0

I am currently working with PHP Simple HTML DOM Parser trying to scrape a site. Here is what i have so far:

$html = file_get_html('https://www.example.com');

// Find all article blocks
foreach($html->find('.plan') as $article) {
    $item['title']     = $article->find('.price', 0)->plaintext;
    $item['intro']   = $article->find('li', 0)->plaintext;
    $item['details'] = $article->find('.button', 0)->href;
    $articles[] = $item;
}

print_r($articles);

The above works fine, however if more than one <li> exists it only returns the first <li> missing out the rest.

Is there a way i can get all list items?

1 Answer 1

1

With the second attribute in the find-function, you define the nth element of the result, that should be returned. In your example, $article->find('li',0) gives you the li element at index 0 (so the first) of the matching elements.

If you want all <li> elements, try this:

$html = file_get_html('https://www.example.com');

// Find all article blocks
foreach($html->find('.plan') as $article) {
    $item['title']   = $article->find('.price', 0)->plaintext;
    $item['intro']   = array(); //define as array
    foreach ($article->find('li') as $li) { //get all <li>-elements as array
        $item['intro'][] = $li->plaintext; //add the plaintext of each single <li> element as new position to the $item['intro'] array
    }
    $item['details'] = $article->find('.button', 0)->href;
    $articles[] = $item;
}

print_r($articles);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.