Доступ к SimpleXMLElements в массиве - PullRequest
0 голосов
/ 19 августа 2010

Я просматривал подобные статьи, такие как , эту , и я не могу заставить его работать, вполне возможно, я просто неправильно понимаю.

У меня есть простой скрипт, который анализирует немного xml и распечатывает определенные поля - мне не хватает доступа к данным объектов SimpleXMLElement.

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 ]

1 голос
/ 19 августа 2010

Если вы действительно не хотите просто передавать элемент 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!
0 голосов
/ 19 августа 2010

Я думаю, у вас есть ошибка, когда вы присваиваете значение массиву:

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

, если у вас есть foreach, почему вы создаете на каждом шаге новый массив $ article = array ();

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