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
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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.