访问数组中的SimpleXMLElements

时间:2010-08-19 12:21:11

标签: php arrays simplexml

我看过像this one这样的类似文章而且我无法让它发挥作用,很可能我只是误解。

我有一个简单的脚本解析了一些xml并打印出特定的字段 - 我正在做的就是访问SimpleXMLElement Objects的数据。

XML(为简洁起见而简化)

<channel>
  <item> 
    <title><![CDATA[Title is in here ...]]></title> 
    <description>Our description is in here!</description>
  </item>
</channel>

PHP

$url = "file.xml";
$xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA);

foreach ($xml->channel->item as $item) {
$articles = array();
$articles['title'] = $item->title;
$articles['description'] = $item->description;
}

到目前为止,一切似乎都没问题。我最终得到了一系列内容,我可以通过print_r确认,这就是我的回复:

Array
(
    [title] => SimpleXMLElement Object
        (
            [0] => Title is in here ...
        )

    [description] => SimpleXMLElement Object
        (
            [0] => Our description is in here!
        )
)

关键问题

如何访问[title] [0]或[description] [0]?

我尝试了几个变种没有成功,很可能是某个新手的错误!

foreach ($articles as $article) {
        echo $article->title;
    }

foreach ($articles as $article) {
        echo $article['title'][0];
    }

foreach ($articles as $article) {
        echo $article['title'];
    }

2 个答案:

答案 0 :(得分:1)

如果您真的不想简单地传递SimpleXMLelement,而是先将值放在数组中......

<?php
// $xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA);
$xlm = getData();

$articles = array();
foreach ($xml->channel->item as $item) {
  // with (string)$item->title you get rid of the SimpleXMLElements and store plain strings
  // but you could also keep the SimpleXMLElements here - the output is still the same.
  $articles[] = array(
    'title'=>(string)$item->title, 
    'description'=>(string)$item->description
  );
}

// ....
foreach( $articles as $a ) {
  echo $a['title'], ' - ', $a['description'], "\n";
}

function getData() {
  return new SimpleXMLElement('<foo><channel>
    <item> 
      <title><![CDATA[Title1 is in here ...]]></title> 
      <description>Our description1 is in here!</description>
    </item>
    <item> 
      <title><![CDATA[Title2 is in here ...]]></title> 
      <description>Our description2 is in here!</description>
    </item>
  </channel></foo>');
}

打印

Title1 is in here ... - Our description1 is in here!
Title2 is in here ... - Our description2 is in here!

答案 1 :(得分:0)

我认为在为数组赋值时会出错:

foreach ($xml->channel->item as $item) {
    $articles = array();
    $articles['title'] = $item->title;
    $articles['description'] = $item->description;
}

如果你有foreach为什么你在每一步创建新数组$ articles = array();

$articles = array();
foreach ($xml->channel->item as $item) {
        $articles['title'] = $item->title;
        $articles['description'] = $item->description;
}