I have the following XML array:
["link"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#311 (1) {
["@attributes"]=>
array(3) {
["type"]=>
string(9) "text/html"
["href"]=>
string(48) "http://twitter.com/bob/statuses/1226112723"
["rel"]=>
string(9) "alternate"
}
}
[1]=>
object(SimpleXMLElement)#312 (1) {
["@attributes"]=>
array(3) {
["type"]=>
string(9) "image/png"
["href"]=>
string(59) "http://a3.twimg.com/profile_images/226895523/Dan_normal.png"
["rel"]=>
string(5) "image"
}
}
}
It's inside a bigger array, I need to get the first and second hef attribute seperatly so that I can put one href as a <a>
link and another with a <img>
.
How can I output each href rather than both togethe开发者_如何学运维r?
Currently trying this:
foreach($entry->link as $link) {
echo $link->attributes()->href;
}
$url = 'http://api.twitter.com/1/favorites/bob.atom';
$feed = simplexml_load_file($url);
$testStop = 0;
foreach($feed->entry as $entry) {
echo 'title: ', $entry->title, "\n";
// store all link/@href in a hashtable
// so you can access them in any order you like
// without resorting to xpath or alike.
$links = array();
foreach($entry->link as $link) {
$links[(string)$link['rel']] = (string)$link['href'];
}
if ( isset($links['image']) ) {
echo '<img src="', $links['image'], '" />', "\n";
}
if ( isset($links['alternate']) ) {
echo '<a href="', $links['alternate'], '" />alternate</a>', "\n";
}
echo "----\n";
if ( 2 < ++$testStop ) die;
}
(currently) prints
title: kolchak: Sometimes I think I need a new butler. But then it's like "Nah, he's still got one thumb. We good."
<img src="http://a1.twimg.com/profile_images/668496250/Picture_14_normal.jpg" />
<a href="http://twitter.com/kolchak/statuses/10648055680" />alternate</a>
----
title: shitmydadsays: "War hero? No. I was a doc in Vietnam. My job was to say "This is what happens when ."
<img src="http://a3.twimg.com/profile_images/362705903/dad_normal.jpg" />
<a href="http://twitter.com/shitmydadsays/statuses/10580558323" />alternate</a>
----
title: shitmydadsays: "I lost 20 pounds...How? I drank bear piss and took up fencing. How the you think, son? I exercised."
<img src="http://a3.twimg.com/profile_images/362705903/dad_normal.jpg" />
<a href="http://twitter.com/shitmydadsays/statuses/10084782056" />alternate</a>
----
But you might also be interested in xsl(t)
You can access the href
attributes using normal array/object access. Just store them in an array for later use:
$hrefs = array();
foreach($array['links'] as $links) {
foreach($links->attributes as $key>=$value) {
if('href' == $key) {
$hrefs[] = $value;
}
}
}
// $href[0] = "http://twitter.com/bob/statuses/1226112723"
// $href[1] = "http://a3.twimg.com/profile_images/226895523/Dan_normal.png"
This makes use of SimpleXMLElement
's attributes()
method.
I don't think that you can access the attributes directly ($elment->@attributes) as this is not a valid syntax.
First href - $xml['link'][0]->attributes()->href
Second href - $xml['link'][1]->attributes()->href
精彩评论