André Santos André Santos - 5 months ago 13
PHP Question

How to access an XML nth element's property value and attribute value

Good, I ask again for your help. I have an xml document (http://radiojoven.6te.net/AirPlayHistory.xml) with several songs and I'm trying to create a code so that it can provide me each song individually xml document, but I'm getting find the right method to do with the code provides all the songs at the same time.

Example: I want to just take the music OLLY MURS - KISS ME, as is the 4 music I made this code:



<?php
$xml = simplexml_load_file("http://radiojoven.6te.net/AirPlayHistory.xml");
foreach($xml->Song as $item)
echo $item->Artist['name'][4] . " - " . $item['title'][4] ."<br>";
?>





but appears all the songs and I do not intend it, but rranjar one code that provides me the requested music. Can I help?

Thank you!

Answer

Use the following code

Note that element position starts from 0, so if you want 4th element it is the 3rd index

$xml = simplexml_load_file("http://radiojoven.6te.net/AirPlayHistory.xml");
$elementNo = 4;
$elepentPos = $elementNo - 1;
echo $xml->Song[$elepentPos]->Artist['name'] . ' --- ' . $xml->Song[$elepentPos]['title'];

Now to describe this further

Attributes are accessed using []

Elements are accessed using object notation

http://www.w3schools.com/php/php_xml_simplexml_get.asp follow this link to get more information