I need help extracting data from a PHP array, after which I need to create an XML tag. I have a string as you can see below. Sometimes there is one data, ie a picture, sometimes there are several pictures
[0]=> "https://test.com/1.jpg"
[1]=> "https://test.com/2.jpg"
[2]=> "https://test.com/3.jpg"
...
I created a php function, which works well with when it encounters a single image, however when it encounters multiple images it returns only the first element (image) in the array.
function Photo($Images)
{
$br=count($Images);
if ($br==1){ return "<photo><url>".$Images."</url><priority><![CDATA[1]]></priority></photo>"; }
elseif ($br>1)
{
$broj=count($Images);
foreach ($Images as $value)
{
for ($i = 0; $i < $broj; $i++) {
}
return "<photo><url>$value</url></photo>";
}
}
}
I need the function to return an XML tag with the URL of the image and the ordinal number in the sequence, eg
<photo> <url> https://test.com/1.jpg </url> <priority> 1 </priority> </photo>
<photo> <url> https://test.com/2.jpg </url> <priority> 2 </priority> </photo>
etc
I have a problem with nested XML and with a return function in PHP. In other words, I need the function to return all the elements of the array, not just the first one.
With echo, he shoots me everything and reports a bug.
I'm learning PHP and I need help
Thanks
Your issue is that you use the return
keyword, which aborts the entire function, and ends the for
loop early, only returning the first value in the array.
Instead, one option is to have a string that contains the current XML that you have, and keep adding onto it until the for
loop completes. After the for
loop, you can return
that string.
function Photo($Images) {
$br = count($Images);
if ($br == 1) {
return "<photo><url>".$Images."</url><priority><![CDATA[1]]></priority></photo>";
} elseif ($br > 1) {
// Start off with an empty string
$imagesString = "";
foreach ($Images as $value) {
// Append to the end of the string
$imagesString .= "<photo><url>$value</url></photo>";
}
return $imagesString;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.