我使用PHP和SimpleXML。
我使用了一个无法正常工作的循环:
foreach($item->Image->attributes()->source as $key => $value)
{
echo $value;
}
在foreach中,我试图告知我想要获得属性中列出的图像的"源"。
上面的$item
是在foreach($xml_content->Section->Item as $item {}
上面的代码周围创建的,(如果你需要知道它来自哪里)
我的对象如下所示:
object(SimpleXMLElement)#36 (4) {
["Text"]=>
string(15) "Vinbergs socken"
["Description"]=>
string(73) "Vinbergs socken ingick i Faurås härad och ligger i Falkenbergs kommun.
"
["Url"]=>
string(44) "http://sv.wikipedia.org/wiki/Vinbergs_socken"
["Image"]=>
object(SimpleXMLElement)#38 (1) {
["@attributes"]=>
array(3) {
["source"]=>
string(113) "http://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Faur%C3%A5s_Vinberg.svg/50px-Faur%C3%A5s_Vinberg.svg.png"
["width"]=>
string(2) "50"
["height"]=>
string(2) "41"
}
}
}
我帖子开头的循环出了什么问题?
您正在尝试迭代字符串,而不是数组
$item->Image->attributes()->source
要迭代Image元素的所有属性,请使用
foreach ($item->Image->attributes() as $attributeName => $attributeValue) {
如果您只想输出源属性的值,请不要迭代,而是使用缩写
echo $item->Image['source']
请参阅此演示和PHP手册