Masayuki Tonoki Masayuki Tonoki - 1 month ago 9
PHP Question

Putting into table from a complicated array using php

SimpleXMLElement Object
(
[@attributes] => Array
(
[version] => 2.0
)

[channel] => SimpleXMLElement Object
(
[title] => Yahoo!ニュース・トピックス - トップ
[link] => http://news.yahoo.co.jp/
[description] => aa
[language] => ja
[pubDate] => Mon, 17 Aug 2015 10:20:57 +0900
[item] => Array
(
[0] => SimpleXMLElement Object
(
[title] => aa
[link] => aa
[pubDate] => aa
[enclosure] => SimpleXMLElement Object
(
[@attributes] => Array
(
[length] => 133
[url] => http://i.yimg.jp/images/icon/photo.gif
[type] => image/gif
)

[0] =>

)

[guid] => yahoo/news/topics/6170952
)

[1] => SimpleXMLElement Object
(
[title] => bb
[link] => bb
[pubDate] => bb
[enclosure] => SimpleXMLElement Object
(
[@attributes] => Array
(
[length] => 133
[url] => http://i.yimg.jp/images/icon/photo.gif
[type] => image/gif
)

[0] =>

)

[guid] => yahoo/news/topics/6170951
)


I've got this array which is very confusing for me as a beginner.
I just want to put the
title, link and pubDate
from
0=> SimpleXMLELement Object
and
1 => SimpleXMLElement Object
which has
aa
and
bb
in them into a my table pulled from mysql.

My table goes like:

Title
PubDate
Link


and I want to put the 'aa' and 'bb' under each of the titles in the table.

This is what I have tried:

foreach($con as $key => $val){
while($key == title){
$Title['title'] = $val;
}
return $Title['title'];
}


What I was trying to do was label the keys and values with
$key
and
$val
, and when
$key = title
, I wanted to put all the titles into one array, but unfortunately it did not work.

Answer

Assuming that $xmlStructure is the structure posted above, your code should look something like:

$items = $xmlStructure->channel->item;
$table = [];
foreach ($items as $item) {
    $table[] = [
        'title' => $item->title,
        'pubDate' => $item->pubDate,
        'link' => $item->link;
    ];
}

At the end of this, your $table array will contain an array of entities, each containing the three fields.

Then, constructing an HTML table (or table of another type) should be fairly straightforward.