【问题标题】:fails fetching XML data from multiple url in one shot一次从多个 url 获取 XML 数据失败
【发布时间】:2016-11-17 05:47:24
【问题描述】:

我的代码是这样的

<?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 进行处理,将数据插入 DB,然后对第二个三分之一做同样的事情,依此类推。

但是在这里,如果我更改 abc.txt 中 url 的顺序,我的代码仅适用于最后一个 url,它仅适用于最后一个 url,并为其他 url 提供以下错误

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

应该修改什么来解决这个问题?

【问题讨论】:

    标签: php mysql xml url


    【解决方案1】:

    这可能是您的 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
    }
    

    【讨论】:

    • 谢谢@scott anderson,你的回答几乎奏效了,但它过去常常在最后取一个空行,所以我尝试了 $url = str_replace(PHP_EOL, '', fgets($fp));效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2015-11-21
    • 2023-01-04
    相关资源
    最近更新 更多