访问对象属性(不进行数组转换即可向下钻取) [英] Accessing Object Properties (Drilling down without array conversion)
问题描述
我最近一直在使用tv_grab_uk_rt来生成电视指南xml文件。我编写了一个脚本,将XML转换为对象,可以循环遍历并插入数据库。在使脚本正常工作的同时,我遇到了一个我希望澄清的问题。
I have recently been working with tv_grab_uk_rt which generates a TV guide xml file. I have written a script to convert the XML into an object which I can the loop through and insert into a database. Whilst I have the script working, I came across an issue I was looking to get clarification for.
将XML放入对象时,我得到以下信息:
When putting the XML to an object I get the following:
SimpleXMLElement Object
(
[@attributes] => Array
(
[date] => Mon, 23 Dec 2013 04:30:01 GMT
[source-info-url] => http://www.radiotimes.com
[source-info-name] => Radio Times XMLTV Service
[source-data-url] => http://xmltv.radiotimes.com/xmltv/channels.dat
[generator-info-name] => XMLTV/0.5.61, tv_grab_uk_rt 1.342, 2011/06/19 06:50:36
[generator-info-url] => http://www.xmltv.org
)
[channel] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => fiver.channel5.co.uk
)
[display-name] => 5*
[icon] => SimpleXMLElement Object
(
[@attributes] => Array
(
[src] => http://www.lyngsat-logo.com/logo/tv/cc/channel5_star.jpg
)
)
)
)
)
假设我要执行以下操作,则将该对象包含在变量 $ xml
中:
Lets say this object is contained within the variable $xml
, if I were to do the following:
foreach($xml->channel as $channel)
{
echo $channel->displayname
}
我知道我可以回显<$的对象属性c $ c> displayname ,在这种情况下为 5 *
。
I realise I would be able to echo the object property of displayname
, in this case 5*
.
但是会发生什么如果我想说回声 src
在这种情况下为 http://www.lyngsat-logo.com/logo/tv/cc/channel5_star。 jpg
,我该如何处理一个对象。例如,我不能
But what happens if I wanted to say echo the src
in this case http://www.lyngsat-logo.com/logo/tv/cc/channel5_star.jpg
, how would I go about doing this with an object. I can't for example do
foreach($xml->channel as $channel)
{
echo $channel->icon->@attributes->src
}
例如使用数组,您可以轻松地完成
With arrays for example you could easily do
foreach($xml['channel'] as $channel)
{
echo $channel['icon']['@attributes']['src'];
}
但不包含对象。而不是陷入无限循环,我发现我可以将对象转换成这样的数组
But not with objects. Rather than getting into endless loops I found I could convert the object to an array like so
foreach($xml->channel as $channel)
{
echo $channel['icon']['@attributes']['src'];
$channelArray = get_object_vars($channel);
}
然后,我可以简单地以数组形式访问属性。
所以我的问题确实是,没有将对象转换为数组,有没有一种方法可以深入研究属性,即
Then I can simply access the properties as an array. So my question really is, without converting the object into an array, is there a way to drill into the properties ie
$xml->channel->0->displayname
推荐答案
每个频道
是 SimpleXMLElement 实例,这样您就可以
Each channel
is a SimpleXMLElement instance so you can
foreach($xml->channel as $channel)
{
echo $channel->icon->attributes()->src;
}
如有疑问,请始终从官方文档入手。
When in doubt always start from the official docs.
这篇关于访问对象属性(不进行数组转换即可向下钻取)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!