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
)
我得到了这个数组,作为一个初学者,它让我很困惑。我只是想把title, link and pubDate
从0=> SimpleXMLELement Object
和1 => SimpleXMLElement Object
有aa
和bb
在他们到我的表从mysql拉。
我的表是这样的:
Title
PubDate
Link
,我想把'aa'和'bb'放在表格中每个标题的下面。
这是我尝试过的:
foreach($con as $key => $val){
while($key == title){
$Title['title'] = $val;
}
return $Title['title'];
}
我想做的是用$key
和$val
标记键和值,当$key = title
时,我想把所有的标题放在一个数组中,但不幸的是它不起作用。
试试这个:
$array_to_get = ['title', 'link', 'pubDate'];
$newArray = [];
$con = $xmlStructure->channel->item; //Object from xml
foreach($con as $key => $val){
if(in_array($key, $array_to_get)){
$newArray['title'] = $val->title;
$newArray['link'] = $val->link;
$newArray['pubDate'] = $val->pubDate;
}
}
print_r($newArray);
假设$xmlStructure是上面发布的结构,您的代码应该看起来像:
$items = $xmlStructure->channel->item;
$table = [];
foreach ($items as $item) {
$table[] = [
'title' => $item->title,
'pubDate' => $item->pubDate,
'link' => $item->link;
];
}
在此结束时,$table数组将包含一个实体数组,每个实体包含三个字段。
然后,构造一个HTML表(或其他类型的表)应该是相当简单的。
实际上,一旦你开始理解发生了什么以及它的结构如何,这个数组一点也不复杂随着时间的推移,继续成为小菜一碟。我不会告诉你怎么做,我将详细解释如何读取这样一个数组以及如何操作,这样你就知道以后该怎么做了。
示例,假设你想访问数组这部分的版本值:
SimpleXMLElement Object
(
[@attributes] => Array
(
[version] => 2.0
)
)
首先你要将它存储在一个变量中数组下的每一层都是这样设置的比如这个数组存储在$container
中//with @attributes you access it as a function, anything with @ is access as a function, example below.
$version = $container->attributes()->['version']
现在说你想访问标题,链接,出版日期等。
你会做
$title = $container->channel->title;
$link = $container->channel->link;
$description = $container->channel->description
//notice how after channel i used it as an object instead of an array , its because after channel it mentions that its an SimpleXMLElement Object.
现在假设你想访问item下所有从0开始的元素。
$collection = $container->channel->item;
保存item的所有元素。为了证明这一点,只需执行print_r($collection),您将看到返回给您的数据集合,并获得其集合的输出,只需执行简单的foreach循环以获取所有值,如下所示:
foreach($collection as $items)
{
echo 'Title: ' . $items->title . '<br/>';
echo 'Link: ' . $items->link . '<br/>';
echo 'Pubdate' . $items->pubDate . '<br/>';
//and so on
}
一旦你理解了这个,你就可以创建你的表或其他你必须做的事情,但你必须首先了解如何读取数组,如