Jump to content

simplexml get element value by name


citricsquid

Recommended Posts

<sizes>
−
<size name="original" width="300" height="300">
http://userserve-ak.last.fm/serve/_/2457865/Basshunter+126073.jpg
</size>
<size name="large" width="126" height="126">http://userserve-ak.last.fm/serve/126/2457865.jpg</size>
<size name="largesquare" width="126" height="126">http://userserve-ak.last.fm/serve/126s/2457865.jpg</size>
<size name="medium" width="64" height="64">http://userserve-ak.last.fm/serve/64/2457865.jpg</size>
<size name="small" width="34" height="34">http://userserve-ak.last.fm/serve/34/2457865.jpg</size>
<size name="extralarge" width="252" height="252">http://userserve-ak.last.fm/serve/252/2457865.jpg</size>
</sizes>

 

How would I get each size by their name? So if I wanted to call "small" or "extralarge"?

 

$xmlData->images->image->sizes->size

 

what comes after that? adding ['extralarge'] after size doesn't work.

Link to comment
https://forums.phpfreaks.com/topic/176747-simplexml-get-element-value-by-name/
Share on other sites

You could do something similar to the following code snippet. They key thing is the use of the SimpleXMLElement::xpath method.

 

<?php

// ...

foreach ($xmlData->images->image as $image)
{
// SimpleXMLElement::xpath returns an array, we only want the first value
$thumb = current($image->sizes->xpath('size[@name="small"]'));
printf(
	'<img src="%s" width="%d" height="%d" alt="%s"><br>'."\n",
	$thumb,
	$thumb['width'],
	$thumb['height'],
	htmlspecialchars($image->title)
);
}

?>

 

The other option would be to manually loop over the different sizes available until you get to the small one, but the XPath way is much prettier.

The other option would be to manually loop over the different sizes available until you get to the small one, but the XPath way is much prettier.

 

I'll try that then, thanks :D I was considering looping, but I assumed it was simple enough to just add ['extralarge'] or an image size somewhere :D

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.