2017-01-05 34 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',則該數組將被添加兩次。 –