Skip to content



[PHP]HTMLScrapingのメモリリーク回避

htmlファイルをスクレイピングする必要があり、HTMLScrapingというライブラリを使用しています。

http://www.rcdtokyo.com/ucb/contents/i000851.php

ライブラリ自体は便利なのですが、どうもgetXmlObject()を呼ぶたびにメモリ使用量が増えていってしまう…

PHP初心者ながらコードを追っていると、どうもgetXmlObject()がコールされるたびに、require ‘xhtml1-transitional_dtd.inc.php’;が呼ばれ、この度にメモリ使用量が大量に増えていっているようだ。

上述のrequire…は、一回呼ばれれば十分なコードでしたのでパッチを当ててみました。

“add 2009/10/12″, “del 2009/10/12″がある行が変更箇所です。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class HTMLScraping
{
 
    // add 2009/10/12
    private $m_format_rule = nil;
 
 
    final public function __construct($cache_dir = '', $gc_max_lifetime = 86400, $gc_divisor = 100)
    {
        ...
 
        // add 2009/10/12
        $this->m_format_rule = require 'xhtml1-transitional_dtd.inc.php';
    }
 
 
    ...
 
    final public function getXhtml($url...) 
    {
        ...
        /*
         * Use Tidy to format HTML if available.
         * Otherwise, use HTMLParser class (is slower and consumes much memory).
         */
        if (extension_loaded('tidy')) {
            $tidy = new tidy;
            $tidy->parseString($data['body'], array('output-xhtml' => true), 'UTF8');
            $tidy->cleanRepair();
            $data['body'] = $tidy->html();
        } else {
            require_once 'HTMLParser.class.php';
            $parser = new HTMLParser;
 
            // del 2009/10/12
            // $format_rule = require 'xhtml1-transitional_dtd.inc.php';
            // $parser->setRule($this->format_rule);
 
            // add 2009/10/12
            $parser->setRule($this->m_format_rule);
 
            $parser->setRoot('html', array('xmlns' => 'http://www.w3.org/1999/xhtml'));
            $parser->setGenericParent('body');
            $parser->parse($data['body']);
            $data['body'] = $parser->dump();
        }       
        ...
 
    }

4873111870
Spidering hacks―ウェブ情報ラクラク取得テクニック101選

4873114047
Debug Hacks -デバッグを極めるテクニック&ツール

Tag .


One Response

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. なぞの人 says

    すばらしいです。ちょうどサーバーの利用制限に引っかかって私もこの問題で悩んでいました。
    おかげで解決の糸口が見えました。