duanhu7615 2017-03-21 12:53
浏览 39
已采纳

为什么我的脚本只将xml文件中的最后一个H2标签保存到数据库中?

I'm trying to store all the H2 tags into my database. I'm using Laravel 5.4 and DomDocument.

How i retrieve the h2 tags:

$htag2 = $dom->getElementsByTagName('h2');

My h2 tags:

<h2> htag2-1 </h2>
<h2> htag2-2 </h2>
<h2> htag2-3 </h2>
<h2> htag2-4 </h2>

This is the output in the database: htag2-4. As you can see it skips the other 3 h2tags in my xml file.

I'm trying to save this using for loop:

for ($i = 0; $i < $htag2->length; $i++) {
 $ts->h2_tag = $htag2->item($i)->nodeValue;
}

Declaration for $ts: $ts = new Scan;

  • 写回答

1条回答 默认 最新

  • douliwang6896 2017-03-21 13:03
    关注

    In your code fist you need to do is to collect all elements in some array, for example:

    $h2Array = [];
    
    for ($i = 0; $i < $htag2->length; $i++) {
        $h2Array[] = $htag2->item($i)->nodeValue;
    }
    

    And then do operation with collected items. Or you can just insert them one by one in for statement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?