donglu1913 2013-07-22 02:46
浏览 25
已采纳

在PHP中从XML中逐行保存数据到文件

I am getting data from another website, removing what I don't need. And would like to store the information I gathered to a file. I have done everything I need but my file writes array every line

Here is the code I am working on:

    $xml = simplexml_load_file('website.xml');

    $item_array = array();
    $item_array[0] = 0;
    $item_array[1] = 2;
    $item_array[2] = 4;
    $item_array[3] = 6;
    $item_array[4] = 8;
    $item_array[5] = 9;
    $item_array[6] = 10;
    $item_array[7] = 11;
    $item_array[8] = 12;
    $item_array[9] = 13;
    $item_array[10] = 14;
    $item_array[11] = 15;
    $item_array[12] = 16;

    $patterns = array();
    $patterns[0] = '/Sum It Up/';
    $patterns[1] = '/=/';
    $patterns[2] = '/Powerball/';
    $patterns[3] = '/MegaBall/';
    $patterns[4] = '/Megaplier/';
    $patterns[5] = '/Bonus Ball/';

    $print = array();
    foreach($item_array as $news){
    echo $xml->channel->item[$news]->title.'<br>';
    $new_string = $xml->channel->item[$news]->description;
    $new_string = preg_replace("/[^A-Za-z0-9 ]/", '', $new_string);
    $new_string = preg_replace($patterns, '', $new_string);
    echo $new_string.'<br>';
    $print[] = array($new_string);
    }

    $filename = 'numbers.txt';
    $handle = fopen($filename, 'w');
    @$output = implode("
", $print);
    fwrite($handle, $output);
    fclose($handle);

I just want to keep the numbers as array and write the numbers to a file in line by line.

  • 写回答

2条回答 默认 最新

  • dongxing1965 2013-07-22 02:50
    关注

    From the discussion below, the problem solved finally. Here should use $print[] = $new_string to make sure $print is one level array. Then you can using var_export or custom style to print it line by line. $print[] means to add an item into this array, if the item is an array already, $print will be an 2 level array.

    -----Old Answer-----

    Using serialize() function, it can serialize an array to string, and then you can write it to a file. Using unserialize() can make the string back to array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化