#14 can't modify meta tag attribute

open
nobody
None
5
2012-10-26
2012-09-22
No

I have class Page, which contains page URL and HTML code. There is also function dom() which returns your class (htmldom) object with loaded html.

Now, I also have one function to set page's meta description/keywords. Here's how it looks:

public function set_meta($name, $content)
{
    //try to get meta tag
    $meta = $this->dom()->find('head meta[name='.$name.']', 0);
    //if there is meta tag, change it's "content" attribute
    if (!empty($meta))
    {
        $meta->content = $content;
    }
    //otherwise, create new html meta tag and append it to <head>
    else
    {
        $tag_head = $this->dom()->find('head', 0);
        if (!empty($tag_head))
            $tag_head->innertext .= '<meta name="'.$name.'" content="'.$content.'" />'."\n";
    }

    //save changed dom back to html, so next call to ->dom() will load this new html
    $this->html = $this->dom()->save();
}

So to set meta description I'd call $page->set_meta('description', 'My description here');

Everything works fine as long as I don't have meta description tag in my page (it is being automatically added to the header). However, if I do have meta description tag, it's contents never get changed, although $meta object exists and it's "content" attribute is being changed. Like it never gets back to the page DOM. Do you have any idea why it works when changing innertext of the , but won't change content attribute of the tag?

I have tried both with and without last line ($this->html = $this->dom()->save();) but nothing changes...

Discussion

  • John Schlick
    John Schlick
    2012-10-26

    First thank you for posting a problem statement with almost all of the information I need. Thats rare.

    $meta->content = something...

    There is no content routine, so it calls the magic method __set in the simple_html_dom_node class.

    Line 765 and 757 (of the current codebase out of trunk) determine what happens when that attribute doesn't exist. (and I haven't looked at the _ array in a while, so I'm not commenting on what this does)

    Then line 759 adds the attribute to the attr array.

    My advice is to do a couple of things. first pull down the sourceforge debugobject project, so that you can turn on debug (simple_html_dom instrumented for the sourceforge debugobject), and then after you confirm that set is properly being called, do a ->dump of the node before and after the call to set to see that the attribute is actually being set.

    Let me know what you find. (as in, if I have time, I will try to recreate this and see what happens, but I've been really busy of late)

     
    Last edit: John Schlick 2012-10-26