PHP - For循环只返回数组中的最后一个变量

Bri*_*nte 0 php arrays loops for-loop

我有一个奇怪的问题,PHP中的for循环只返回数组中的最后一项.

该数组是使用XML文件中的SimpleXML创建的.

代码应该返回:

<tags><tag value="Tag1" /><tag value="Tag2" /><tag value="Tag3" /></tags>
Run Code Online (Sandbox Code Playgroud)

但相反,我得到:

<tags><tag value="Tag3" /></tags>
Run Code Online (Sandbox Code Playgroud)

因此,无论我在那里有多少项,它都会忽略除阵列中最后一项之外的所有项目.

谁能看到我做错了什么?

这是代码:

<?php

function gettags($xml)
{
    $xmltags = $xml->xpath('//var[@name="infocodes"]/string');
    return $xmltags[0];
}

//Path to the XML files on the server
$path = "/xmlfiles/";

//Create an array with all the XML files
$files = glob("$path/*.xml");

foreach($files as $file)
{
    $xml = simplexml_load_file($file);
    $xmltags = gettags($xml);

//Using the , character split the values coming from the $xmltags into an array
$rawtags = explode(',', $xmltags);

//Loop through the tags and add to a variable. Each tag will be inside an XML element - <tag value="tagname" />
for ($i = 0; $i <count($rawtags); $i++){
    $tags = '<tag value="' . $rawtags[$i] . '" />';
}

//Replace HTML escaped characters (ä, å, ö, Å, Ä, Ö) and the | character with normal characters in the tags variable
$tagsunwantedchars = array("&Ouml;", "&Auml;", "&Aring;", "&ouml;", "&auml;", "&aring;", "|");
$tagsreplacewith = array("Ö", "Ä", "Å", "ö", "ä", "å", " - ");
$tagsclean = str_replace($tagsunwantedchars, $tagsreplacewith, $tags);

//Create the full tag list and store in a variable
$taglist = "<tags>$tagsclean</tags>";

}

echo $taglist;

?>
Run Code Online (Sandbox Code Playgroud)

这是XML文件:

<wddxPacket version='1.0'>
    <header/>
    <data>
        <struct>
            <var name='infocodes'>
                <string>Tag1,Tag2,Tag3</string>
            </var>
        </struct>
    </data>
</wddxPacket>
Run Code Online (Sandbox Code Playgroud)

Mat*_*ijs 12

简单的bug:使用$tags .=而不是$tags =在循环中:

$tags = '';
for ($i = 0; $i <count($rawtags); $i++){
    $tags .= '<tag value="' . $rawtags[$i] . '" />';
}
Run Code Online (Sandbox Code Playgroud)