2013-03-21 35 views
0

我遇到了一個問題,我有一個應該搜索匹配字符串的XML文件的腳本。 這裏是我的腳本:Preg match找不到正確的字符串

<?php 
$file = "klein.xml"; 
$lines = file($file); 
foreach ($lines as $line_num => $line) 
{ 
    echo htmlentities($line); 
    echo "<br>"; 

} 

    if (preg_match("/message/", htmlentities($line), $found)) 
    { 
    echo "Found!"; 
    echo $found[0]; 
    echo "test"; 
    } 
    else 
    { 
     echo "Not Found!"; 
    } 
?> 

,這是XML文件IM與合作:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<product-data> 
<message-header> 
<message-id>OR-1361163557-gr</message-id> 
<message-timestamp>1361163557</message-timestamp> 
<export-version current_version="1">OGPDX-2.01.01</export-version> 
</message-header> 
</product-data> 

問題是,當我預浸匹配「產品」是否能夠正常工作,但是當我嘗試預浸匹配另一個字符串即'消息'它不工作?

我很好奇的解決方案,在此先感謝!

+0

什麼意思是「不起作用」?難道它找不到你期待的所有比賽嗎?它與你不想要的東西匹配嗎? – 2013-03-21 08:06:48

+0

它不會找到我期待的所有匹配 – 2013-03-21 08:07:36

+0

哪一個不找它? – 2013-03-21 08:08:06

回答

0

你能檢查這段代碼嗎,我注意到你把if循環放在foreach以外;因此只有最後一行被執行。

<?php 
$file = "klein.xml"; 
$lines = file($file); 
foreach ($lines as $line_num => $line) 
{ 
    if (preg_match("/message/", htmlentities($line), $found)) 
    { 
    echo "Found ".$found[0]."<br />"; 
    } 
} 
?> 
+0

感謝他做的工作! – 2013-03-21 08:16:16

0

的問題是你的邏輯:你只檢查$line最後的值,它是包含</product-data>

0

所以你在搜索?你的xml的一行...
當你搜索「產品」(在最後一行)$行是在最後一行。

foreach ($lines as $line_num => $line) 
{ 
    if (preg_match("/message/", $line , $found)) 
    { 
    echo "Line: $line_num - ".$found[0]." <br>"; 
    } 
}