2016-07-14 46 views
1

我的代碼看起來像這樣失敗一次性從多個網址獲取XML數據

<?php 
include 'dbconnection.php'; 
include 'date.php'; 

function fetch_url_content() 
{ 
    $conn = get_dbConnection(); 

    $fp = fopen("abc.txt", "r") or die("Unable to open file!"); 
    $count = 0; 
    while (!feof($fp)) 
    { 

    $url = fgets($fp); 

    //read feed into SimpleXML object 
    $sxml = simplexml_load_file($url); 


    foreach($sxml->channel->item as $type){ 
    $description = $type->description; 
    $dom = new DOMDocument; 
    $dom->loadHTML($description); 
    $a=array(); 

    foreach ($dom->getElementsByTagName('td') as $node){ 
    array_push($a,$node->nodeValue); 
    } 
    $a1 = $type->title; 
    $a2 = addslashes($a[3]); 
    $a3 = $a[5]; 
    $a4 = date_correction('30-'.$a[1]); 

    $sql = "INSERT IGNORE INTO my_table(`c1`,`c2`,`c3`,`c4`) 
    VALUES ($a1,'$a2',$a3,'$a4')"; 
    $sth = $conn->prepare($sql); 
    $sth->execute(); 

    $count++; 
     } 
    } 
    echo "successfully inserted ".$count." entries to the DB"; 
} 
fetch_url_content(); 
?> 

我的abc.txt文件看起來像這樣

http://example.com/RssNAV.aspx?swise=y&mf=43 
http://example.com/RssNAV.aspx?swise=y&mf=36 
http://example.com/RssNAV.aspx?swise=y&mf=4 
http://example.com/RssNAV.aspx?swise=y&mf=62 

這裏在上面的代碼我嘗試採取把它的第一個url處理,將數據插入到數據庫中,然後對第二個數據做相同的處理,依此類推。

但在這裏我的代碼只對最後的URL工作的很好,如果我改變的URL中的順序的abc.txt它僅在過去的網址做工精細,並提供了以下錯誤給其他網址的

Warning: simplexml_load_file(): http://example.com/RssNAV.aspx?swise=y&mf=43%0D%0A:4: parser error : Extra content at the end of the document in C:\xampp\htdocs\v\xml\fetch_xml_data.php on line 21 

Warning: simplexml_load_file(): <body> in C:\xampp\htdocs\v\xml\fetch_xml_data.php on line 21 

應該是什麼修改來解決這個問題?

回答

0

這可能是abc.txt文件中行結尾的結果。 如果文件有Windows新行字符,請嘗試使用Unix新行字符保存它。 如果這是不可能的,你可以像這樣的東西取代你與fgets()解決方案:

$file = fopen("abc.txt,"r"); 
$text = fread($file, filesize("abc.txt")); 
$lines = explode(PHP_EOL, $text); 
foreach($lines as $line) 
{ 
    // Do something 
} 
+0

謝謝@scott安德森你的答案几乎工作,但它曾經採取一個空行末於是我又試着$ url = str_replace(PHP_EOL,'',fgets($ fp));它運行良好。 – aries12