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
的{{1}}和0=> SimpleXMLELement Object
1 => SimpleXMLElement Object
和aa
放入我从mysql中提取的表中。
我的表格如下:
bb
我希望在表格的每个标题下加上'aa'和'bb'。
这就是我的尝试:
Title
PubDate
Link
我尝试做的是用 foreach($con as $key => $val){
while($key == title){
$Title['title'] = $val;
}
return $Title['title'];
}
和$key
标记键和值,当$val
时,我想把所有标题放到一个数组中,但不幸的是没用。
答案 0 :(得分:2)
试试这个:
$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);
答案 1 :(得分:1)
假设$ xmlStructure是上面发布的结构,您的代码应该类似于:
$items = $xmlStructure->channel->item;
$table = [];
foreach ($items as $item) {
$table[] = [
'title' => $item->title,
'pubDate' => $item->pubDate,
'link' => $item->link;
];
}
最后,$ table数组将包含一个实体数组,每个实体包含三个字段。
然后,构建一个HTML表(或另一种类型的表)应该相当简单。
答案 2 :(得分:1)
实际上,一旦你开始理解正在发生的事情以及它的结构如何,那个数组就不复杂了 随着时间的推移,继续变得小菜一碟。而不是我告诉你该怎么做我将详细解释如何阅读这样的阵列以及如何去做,这样你将会知道将来该做什么。
示例,假设您要访问数组的此部分中的版本值:
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']
现在说你要访问标题,链接,pubdate等。
你会做的$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.
现在假设您要访问项目下的每个元素,其中的值从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
}
一旦你理解了这一点,那么你就可以创建你的表或者你必须做的其他事情,但是你必须先了解如何读取这样的数组。