Search code examples
phparraysobjectsimplexmlsitemap

Add SimpleXMLElement Object to Array


I have and object array as displayed below. Im having trouble adding to this object array as i keep getting an error. Here is how it is at the moment:

SimpleXMLElement Object
(
  [url] => Array
     (
        [0] => SimpleXMLElement Object
            (
                [loc] => http://jbsoftware.co.uk/
                [lastmod] => 2015-02-02
                [changefreq] => monthly
                [priority] => 1.0
            )
      )
)

Now to add to the end of this i am doing the following:

$note="
    <url>
       <loc>{$actual_link}</loc>
       <lastmod>{$date}</lastmod>
       <changefreq>monthly</changefreq>
       <priority>1.0</priority>
    </url>
    ";
    $sxe = new SimpleXMLElement($note);
    $page[] = $sxe;

Which in turn provides me with this error....

Fatal error:  controller::generateSitemap() [<a href='controller.generatesitemap'>controller.generatesitemap</a>]: Cannot create unnamed attribute

Could anyone please let me know why i cannot simply add this onto the end of the current object array? This one has really got me stumped.


Solution

  • $page is not an array (or an array-object that won't mean anything), it is an object (an instance of the class). So you can't use the array methods with it. You can only use available simpleXMLElement class methods.

    For your particular needs, simpleXMLElement doesn't offer any methods to append as a child an other simpleXMLElement instance. However you can use the addChild method to build the subtree element by element:

    $url = $page->addChild('url');
    $loc = $url->addChild('loc', "{$actual_link}");
    $lastmod = $url->addChild('lastmod', "{$date}");
    ...
    

    $url, $loc and $lastmod are new simpleXMLElement instances.