2014-01-05 60 views
0

我正在使用strip_tags從xml文件中剝離標籤,並且在數組大小很小時工作得很好,但如果頁面很大,它總是崩潰。這裏是我的腳本,可用於最多100個值但崩潰的更大的價值strip_tags崩潰的價值很大

 preg_match_all("/<image:caption>.*?<\/image:caption>|<image:loc>.*?<\/image:loc>|<loc>.*?<\/loc>/", $str, $results); 
     $arr = array_chunk(array_map('strip_tags', $results[0]), 1000); 

     for($i=0;$i < 1000;$i++){ 
     for($j=0;$j < 1000;$j++){ 


     $output=$arr[$i][$j]. '</br>'; 


     echo $output; 
     } 

     } 

它會去掉這些值很好,但對於更大的文件崩潰。

 <urlset> 

     <url><loc>/1366x768/citroen-ds-cabrio-auto-car-wallshark-com-228615.html</loc><image:image><image:loc>s/1366x768/citroen-ds/228615/citroen-ds-cabrio-auto-car-wallshark-com-228615.jpg</image:loc><image:caption>Citroen Ds Cabrio Auto Car Wallshark Com Walpapers</image:caption></image:image></url> 

      <url><loc>/1366x768/citroen-ds-cars-citro-n-cabrio-213157.html</loc><image:image><image:loc>s/1366x768/citroen-ds/213157/citroen-ds-cars-citro-n-cabrio-213157.jpg</image:loc><image:caption>Citroen Ds Cars Citro N Cabrio Walpapers</image:caption></image:image></url> 

      <url><loc>/1366x768/citroen-ds-citro-n-pictures-95569.html</loc><image:image><image:loc>s/1366x768/citroen-ds/95569/citroen-ds-citro-n-pictures-95569.jpg</image:loc><image:caption>Citroen Ds Citro N Pictures Walpapers</image:caption></image:image></url> 
     </urlset> 
+0

爲什麼你到底是用正則表達式解析XML?改爲使用XML解析器! – ThiefMaster

+0

@ThiefMaster哪一個會更快 – Priya

+1

@ThiefMaster它的遠程文件,我不認爲我們可以解析遠程文件 – Priya

回答

1

你可以試試這個:

<pre><?php 

$dom = new DOMDocument(); 
@$dom->load('Remotefile.xml'); 

$urls = $dom->getElementsByTagName('url'); 

foreach ($urls as $url) { 
    $image = $url->getElementsByTagName('image')->item(0); 
    $imageChildren = $image->childNodes; 

    $result[] = array('loc' => $url->getElementsByTagName('loc')->item(0)->textContent, 
         'imgloc' => $imageChildren->item(0)->textContent, 
         'imgcap' => $imageChildren->item(1)->textContent); 
} 

$stmt = $dbh->prepare ("INSERT INTO urls (loc, imageloc, imagecap) VALUES (:loc, :imgloc, :imgcap)"); 

foreach ($result as $res) { 
    $stmt -> bindParam(':loc', $res['loc']); 
    $stmt -> bindParam(':imgloc', $res['imgloc']); 
    $stmt -> bindParam(':imgcap', $res['imgcap']); 
    $stmt -> execute(); 
} 

一個正則表達式的方法:

$pattern = <<<'LOD' 
~ 
    <url>            \s*+ 
    <loc>   (?<loc> [^<]++) </loc>   \s*+ 
    <image:image>          \s*+ 
    <image:loc>  (?<imgloc> [^<]++) </image:loc>  \s*+ 
    <image:caption> (?<imgcap> [^<]++) </image:caption> \s*+ 
    </image:image>          \s*+ 
    </url> 
~x 
LOD; 

preg_match_all($pattern, $str, $matches, PREG_SET_ORDER); 

/* this foreach part is only for cosmetic and is totally useless */ 
foreach($matches as &$match) { 
    foreach($match as $k=>$m) { 
     if (is_numeric($k)) unset($match[$k]); 
    } 
} 
print_r($matches); 
+0

致命錯誤:調用 – Priya

+0

@ user3026718中的非對象上的成員函數item():您的文件是否包含沒有圖像或loc標記的url標記?或者部分結構與您的示例不同? –

+0

沒有我的示例文件與原始文件相同 – Priya