The Wolf
The Wolf

Reputation: 195

$element = $html->find('a') does not return exact array Simple DOM

I have this code

<?php
    require_once('/simplehtmldom_1_5/simple_html_dom.php');
    // Create DOM from URL or file
        $html = str_get_html('<html><body><a href="http://www.google.com/">Google</a><br /><a  href="http://www.bing.com/">Bing</a></body></html>');
    // Find all links 
        $element = $html->find('a');
    print_r($element);
?>

From the html that loaded, it contains 2 'a' elements, namely:

  1. http://www.google.com/
  2. http://www.bing.com/

So, what should I expect to print_r($element) should be an array containing these two, but instead it prints a rather super raw array.

Anything I need to change to have these output? Note that contents of the array should be string

Array
(
    [0] => http://www.google.com/
    [1] => http://www.bing.com/
)

Thanks in advance and more power.

Upvotes: 0

Views: 186

Answers (1)

Daniel
Daniel

Reputation: 18682

print_r($html->find('a')) or print_r($element) gives you array of two nodes but it is very complex. Also, it contains objects, so you are able to get href attribute value and store it in array.

This works:

<?php
    require_once('/simplehtmldom_1_5/simple_html_dom.php');
    // Create DOM from URL or file
        $html = str_get_html('<html><body><a href="http://www.google.com/">Google</a><br /><a  href="http://www.bing.com/">Bing</a></body></html>');

        $output = array();
        foreach($html->find('a') as $element) 
            $output[] = $element->href;

        echo '<pre>' . print_r($output, TRUE) . '</pre>'; // echo output array as preformatted text
?>

Output:

Array
(
    [0] => http://www.google.com/
    [1] => http://www.bing.com/
)

Upvotes: 1

Related Questions