Getting values from XML elements which has the same names using PHP
I have a problem in getting the values from all the 3 IMAGE elements coz they have the same name. Below is my xml feed
<FOUND>
<IMAGES>
<IMAGE>
<SMALL>images/small.jpg</SMALL>
<MED>images/med.jpg</MED>
<LARGE>images/large.jpg</LARGE>
<EXTRAL>images/extra.jpg</EXTRAL>
</IMAGE>
<IMAGE>
<SMALL>images1/small.jpg</SMALL>
<MED>images1/med.jpg </MED>
<LARGE>images1/large.jpg</LARGE>
<EXTRAL>images1/extra.jpg</EXTRAL>
</IMAGE>
<IMAGE>
<SMALL>images2/small.jpg</SMALL>
<MED>images2/med.jpg </MED>
<LARGE>images2/large.jpg</LARGE>
<EXTRAL>images2/extra.jpg</EXTRAL>
</IMAGES>
</FOUND>
I have written a function in php that will return the first block.
function images($id){
$xml=simplexml_load_file("feed.xml");
foreach ($xml->FOUND->IMAGES as $image)
{
$imagearr[]=array(
'small'=>$image->IMAGE->SMALL,
'med'=>$image->IMAGE->MEDIUM,
'large'=>$image->IMAGE->LARGE,
'xl'=>$image->IMAGE-> EXTRAL开发者_Python百科,
);
}
return $imagearr;
}
How do I get to grab all the 3 IMAGE elements? I need to use the returned value in to the below html table
<table width="200" border="1">
<tr>
<td>small</td>
<td>medium</td>
<td>large</td>
</tr>
<tr>
<td>small</td>
<td>medium</td>
<td>large</td>
</tr>
<tr>
<td>small</td>
<td>medium</td>
<td>large</td>
</tr>
</table>
Any help will be much appreciated
I would use xPath to return an array.
Try this:
$xml = simplexml_load_file('feed.xml');
$results = $xml->xpath('//IMAGE');
var_dump($results);
Output ...
array(3) {
[0]=>
object(SimpleXMLElement)#2 (4) {
["SMALL"]=>
string(16) "images/small.jpg"
["MED"]=>
string(14) "images/med.jpg"
["LARGE"]=>
string(16) "images/large.jpg"
["EXTRAL"]=>
string(16) "images/extra.jpg"
}
[1]=>
object(SimpleXMLElement)#3 (4) {
["SMALL"]=>
string(17) "images1/small.jpg"
["MED"]=>
string(16) "images1/med.jpg "
["LARGE"]=>
string(17) "images1/large.jpg"
["EXTRAL"]=>
string(17) "images1/extra.jpg"
}
[2]=>
object(SimpleXMLElement)#4 (4) {
["SMALL"]=>
string(17) "images2/small.jpg"
["MED"]=>
string(16) "images2/med.jpg "
["LARGE"]=>
string(17) "images2/large.jpg"
["EXTRAL"]=>
string(17) "images2/extra.jpg"
}
}
You'll then be able to iterate over the results with something like
foreach($results as $row)
{
print $row->SMALL;
}
Hope that helps
to stick a bit more with you original php code, you could try something like this:
$xml=simplexml_load_file("feed.xml");
$imagearr= array();
foreach ($xml->IMAGES->IMAGE as $image)
{
$imagearr[]=array(
'small'=>$image->SMALL,
'med'=>$image->MEDIUM,
'large'=>$image->LARGE,
'xl'=>$image->EXTRAL);
}
return $imagearr;
精彩评论