0

I'm trying to pull the links off of a bunch of webpages and report them in tables. I have this function, get_links($pageId), which is supposed to get the contents of the page and pull out the values and href attributes of each anchor tag.

function get_links($pageId) {
    $page_contents = file_get_contents('http://www.mysite.com/?p='.$pageId);
    $html = new DOMDocument();
    @$html->loadHTML($page_contents);
    $anchors = $html->getElementsByTagName('a');
    $link_array = array();
    foreach($anchors as $anchor) {
        if (!empty($anchor->nodeValue)) {
            $text = $anchor->nodeValue;
            $link = $anchor->getAttribute('href');
            $link_array[$text] = $link;
        }
    }
    return $link_array;
}

When I run this function on one of the pages, it returns nothing. For example, if I call:

$page_links = get_links('someId');
foreach($page_links as $text->$link) {
    //my print functions
};

I get "Fatal error: Cannot access empty property" for the foreach line.

Echoing $text and $link in the foreach($anchors) loop works fine. So does echoing the values from $link_array after the loop. But echoing the keys doesn't. If I put in this test right after the loop:

foreach($link_array as $text->$link) {echo $text;}

I get this error: "Catchable fatal error: Object of class stdClass could not be converted to string."

Why would it print alright during the loop but be treated as an object when I put it in an array to return?

1 Answer 1

1

You're trying to assign the iterated valutes of the foreach loop to an object's attribute. I think you actually want

foreach($link_array as $text => $link) { echo $text;}

instead.

Saying $text->$link is telling PHP to take the current foreach iterated value, and assign it to a $link property of the $text object - however, $text and $link are not objects at that point, so you're assigning to non-existence attributes of a non-existent object, causing the "Cannot access empty property" error.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 $text => $link NOT $text->$link. Read the error message.
Duh. Thank you. It's been a while since I've coded in PHP...the syntax errors always get me!

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.