2013-03-21 47 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>"; 
    } 
}