2017-01-05 30 views
0

我有一个问题...我想知道我的XML文件中的URL或TITLE是否包含一些指定的关键字。如果是,则应将其添加到指定的产品中。如果不是,则应该在指定的产品中添加“Nothing”。XML:带两个循环的appendChild()? (PHP)

但我的问题是,我没有编程它的知识,以便程序检查数组中的关键字是否在URL或TITLE中。因为如果不是数组中的第一个关键字是在URL或TITLE中,它会一直进入其他部落,并添加“Nothing”... 如何说programm只允许在程序中添加“Nothing”检查了$searches阵列中的7个关键字?

此外,程序必须考虑将3以上的关键字值保存为“PlayStation”,而不是“PS3”,“PS4”或“PSN”!

另外,如何将它们添加到我的产品? - 我不认为我的代码下面就是干这个......

代码:

$searches = ["Steam", "Uplay", "Xbox", "Nintendo", "PS3", "PS4", "PSN"]; 

function isContaining($searches, $titleTag, $urlTag, $productTag, $path){ 

    $dom = new DOMDocument('1.0', 'utf-8'); 
    $dom->preserveWhiteSpace = false; 
    $dom->formatOutput = true; 
    $dom->load($path); 
    $root = $dom->documentElement; 

    $markerTitle = $root->getElementsByTagName($titleTag); 
    $markerURL = $root->getElementsByTagName($urlTag); 

    $plat = array(); 

    for($i = $markerTitle->length - 1; $i >= 0 ; $i--){ 

     $title = $markerTitle->item($i)->textContent; 
     $url = $markerURL->item($i)->textContent; 

     $co = count($searches); 

     for($j = 0; $j < $co; $j++){ 
      if(stripos($title, $searches[$j]) !== false){ 
       if($j > 4){ 
        array_push($plat, "PlayStation"); 
       }elseif($j < 5){ 
        array_push($plat, $searches[$j]); 
       } 
      }elseif(stripos($url, $searches[$j]) !== false){ 
       if($j > 4){ 
        array_push($plat, "PlayStation"); 
       }elseif($j < 5){ 
        array_push($plat, $searches[$j]); 
       } 
      }elseif($j == 7 && stripos($url, $searches[$j]) == false){ 
       array_push($plat, "Nothing"); 
      } 
     } 
    } 

    array_reverse($plat); 
    print_r($plat); 
    $c = count($plat); 

    for($i = 0; $i < $c; $i++){ 
     $node = $dom->createElement('plat', $plat[$c]); 
     $dom->getElementsByTagName($productTag)->item($i)->appendChild($node); 
    } 


    $dom->saveXML(); 
    $dom->save($path); 
} 

isContaining($searches, "name", "link", "product", $gamesplanetPath); 

问候,并感谢您!

回答

1

你可以试试这个下面的代码来代替你的内部for循环:

$productFound = false; 
for($j = 0; $j < $co; $j++){ 
    if(stripos($title, $searches[$j]) !== false){ 
     if($j > 3){ 
      array_push($plat, "PlayStation"); 
     }else{ 
      array_push($plat, $searches[$j]); 
     } 
     $productFound = true; 
    }elseif(stripos($url, $searches[$j]) !== false){ 
     if($j > 3){ 
      array_push($plat, "PlayStation"); 
     }else{ 
      array_push($plat, $searches[$j]); 
     } 
     $productFound = true; 
    } 
} 
if($productFound == false){ 
    array_push($plat, "Nothing"); 
} 

注:从0

数组索引开始关于你的最后一个问题

我怎么能将它们添加到我的产品?

我不知道你的意思是加入你的产品。

+0

谢谢,你的代码可以帮助我! - 但现在我想将我的数组中的值添加到指定的产品。你知道我的意思? 我想用DOMDocument创建一个新的元素,并将数组中的值附加到指定的产品。所以一个新的属性。我该怎么做... 问题是,我的代码告诉我,具有值的数组并不像产品列表一样长。但那不可能! 我们保存每一个价值或说不出口! 你知道我的意思吗? – Jan

+0

@Jan,数组可能比您的产品列表更长。如果一个URL包含多个关键字,例如它包含'steam'和'xbox',则该数组将被添加两次。 –