将SimpleXMLElement对象添加到Array

时间:2015-02-09 13:16:50

标签: php arrays object simplexml sitemap

我有和对象数组如下所示。我无法添加到此对象数组,因为我不断收到错误。 现在是这样的:

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

现在添加到此结尾我正在执行以下操作:

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

反过来又为我提供了这个错误....

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

有谁能请让我知道为什么我不能简单地将它添加到当前对象数组的末尾? 这个让我很难过。

1 个答案:

答案 0 :(得分:1)

$page不是数组(或者不是任何意义的数组对象),它是一个对象(类的一个实例)。所以你不能使用它的数组方法。您只能使用available simpleXMLElement class methods

对于您的特定需求,simpleXMLElement不提供任何方法作为子项附加到其他simpleXMLElement实例。但是,您可以使用addChild方法按元素构建子树元素:

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

$url$loc$lastmod是新的simpleXMLElement实例。

相关问题