if else语句使用foreach循环(Xml)

时间:2017-05-16 02:22:14

标签: php xml

执行时,结果往往重复

输出为:stringDogDogDogDogDogDog 或DogDogDogDogDogDogDog

虽然它应该是字符串或狗

<?php  
$name = $_POST['name']; //node
$search = $_POST['search']; //value to be search
$xml = simplexml_load_file("patient.xml");

foreach ($xml ->patients as $patients) {
if ($search == $patients -> $name ) {
    echo "string";      
}
elseif ($search != $patients -> $name ) {
    echo "Dog";

}}?>

1 个答案:

答案 0 :(得分:1)

你的问题很清楚,所以我的回答完全基于我对所需功能的假设。

您有一个XML文件,并且您正在搜索字段以查找给定值。 XML文件有多个“患者”,因此您可以遍历每个“患者”并测试是否匹配。

如果在文件中找到匹配项,则输出“string”,否则您想输出dog。

你看到'stringDogDog ...'的原因是因为条件是在每个“病人”上执行的。有多个“患者”产生输出。

在下面的示例中,我将默认值设置为“Dog”。然后,如果找到匹配,我正在更新输出变量。

// Default output should be dog.
$output = 'Dog';

foreach ( $xml->patients as $patients ) {
    if ( $search === $patients->$name ) {
        $output = 'string';
        break; // we have our match so stop the loop.      
    }
    // no else here or we're going to end up with the long output again...
}

echo $output;
相关问题