Показаны сообщения с ярлыком Парсинг. Показать все сообщения
Показаны сообщения с ярлыком Парсинг. Показать все сообщения

вторник, 25 января 2011 г.

Парсим курс валют

Код - пример #1
1
2
3
4
5
6
7
$url = 'http://www.cbr.ru/scripts/XML_daily.asp?date_req='.date("d/m/Y");
$buf = file_get_contents($url);
if($buf) {
 $xmldoc = new SimpleXMLElement($buf);
 $result = $xmldoc->Xpath("//Valute[@ID='R01239']"); //R01239 код евро
 echo $result[0]->Value;
}
Скопипастил

понедельник, 27 декабря 2010 г.

Парсер простого HTML

Убирает не закрыте, не нужные теги и атрибуты. Выводит отчет.
Код - пример #1
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
 
error_reporting(-1);
 
class MyHtmlTidy
{
    const
        TAG  = '<(?:"[^"]*"|\'[^\']*\'|[^\'">])*>',
        ATTR = '\w++\s*=\s*"[^"]++"|\w++\s*=\s*\'[^\']++\'|\w++\s*=\s*[^\s]++';
 
    private
        $_goodTags  = array('b', 'i', 'u', 's', 'p', 'a', 'img', 'br', 'hr'),
        $_selfClose = array('img', 'br', 'hr'),
        $_goodAttrs = array(
                      'a'   => array('href', 'title'),
                      'img' => array('src', 'alt')),
        $_nest      = array();
 
    public
        $errors = array();
 
    public function preparse($html)
    {
        $this->_nest = array();
        $this->errors = array();
        $text = preg_replace_callback('/('.self::TAG.')/Uus', array($this, '_replace'), $html);
        if (!empty($this->_nest)) {
            $this->errors[] = 'Unclosed tags ' . implode(', ', $this->_nest);
            $text .= '</' . implode('></', array_reverse($this->_nest)) . '>';
        }
        return $text;
    }
 
    private function _replace($matches)
    {
        $tag = $matches[1];
 
        preg_match('/^<\/?(\w++)/', $tag, $m);
        $tagName = strtolower($m[1]);
        $isSelfClosed = $tag{strlen($tag) - 2} == '/';
        $attrs = trim(substr($tag, strlen($m[0]), ($isSelfClosed ? -2 : -1)));
 
        if (!in_array($tagName, $this->_goodTags)) {
            $this->errors[] = 'Tag ' . $tagName . ' is deprecated';
            return '';
        }
 
        // Closing tag
        if ($tag{1} == '/') {
            if (empty($this->_nest) || end($this->_nest) != $tagName) {
                $this->errors[] = 'Odd close tag ' . $tagName;
                return '<' . $tagName . '></' . $tagName . '>';
            }
            array_pop($this->_nest);
            return '</' . $tagName . '>';
        }
 
        // Open tag or self-closing tag
        $isSelfClosed = $isSelfClosed || in_array($tagName, $this->_selfClose);
 
        if (!$isSelfClosed) {
            $this->_nest[] = $tagName;
        }                       
 
        if (!isset($this->_goodAttrs[$tagName])) {
            // No attributes at all
            if (strlen($attrs)) {
                $this->errors[] = 'Tag ' . $tagName . ' cannot have attributes';
            }
            $attrs = '';
        } else {
            // Check every attribute
            preg_match_all('/'.self::ATTR.'/Uus', $attrs, $m);
            $attrs = $m[0];
            foreach ($attrs as $i => $attr) {
                $p = strpos($attr, '=');
                $attrName = strtolower(trim(substr($attr, 0, $p)));
                if (!in_array($attrName, $this->_goodAttrs[$tagName])) {
                    $this->errors[] = 'Wrong ' . $tagName . ' attribute ' . $attrName;
                    unset($attrs[$i]);
                } else {
                    $attrs[$i] = $attrName . '=' . trim(substr($attr, $p + 1));
                }
            }
            $attrs = count($attrs) ? (' ' . implode(' ', $attrs)) : '';
        }
   
        return '<' . $tagName . $attrs . ($isSelfClosed ? '/>' : '>');
    }
}
 
$t = new MyHtmlTidy();
 
$html = <<<HTML
<p class='blabla'>dslkldsldslsd<br>
kjksdjsdk<a href="http://thesite.name/path" target="_new" title="ololo" onclick="javascript:doit('xxx')">djdkjdk</a>
<img src=0.gif alt='pysh-pysh'>
ds;lsd;; <b>skjskjsk kjdkjdkd
HTML;
 
header('Content-type: text/plain');
 
echo $html;
echo "\n===========================\n";
 
$preparsed = $t->preparse($html);
if (!empty($t->errors)) {
    echo implode("\n", $t->errors);
    echo "\n===========================\n";
}
echo $preparsed;
Выводит:
Код - пример #1
<p class='blabla'>dslkldsldslsd<br>
kjksdjsdk<a href="http://thesite.name/path" target="_new" title="ololo" onclick="javascript:doit('xxx')">djdkjdk</a>
<img src=0.gif alt='pysh-pysh'>
ds;lsd;; <b>skjskjsk kjdkjdkd
===========================
Tag p cannot have attributes
Wrong a attribute target
Wrong a attribute onclick
Unclosed tags p, b
===========================
<p>dslkldsldslsd<br/>
kjksdjsdk<a href="http://thesite.name/path" title="ololo">djdkjdk</a>
<img src=0.gif alt='pysh-pysh'/>
ds;lsd;; <b>skjskjsk kjdkjdkd</b></p>
Скопипаситл с пыхи

среда, 15 декабря 2010 г.

Удобный класс для парсинга HTML на PHP

Сам класс с примерами работы:
Код - пример #1
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
<?php

$html = gzdecode(file_get_contents('http://habrahabr.ru/'));

$saw = new nokogiri($html);
var_dump($saw->get('a.habracut')->toArray());
/* На выходе: Array(6) { [0]=> array(3) { 
 ["class"]=> string(8) "habracut"
 ["href"]=> string(56) "http://habrahabr.ru/blogs/google_chrome/110099/#habracut"
 ["#text"]=> string(29) "Читать дальше >" } [1]=> ....
*/ 
var_dump($saw->get('ul.panel-nav-top li.current')->toArray());
/* На выходе: array(2) {
 ["class"]=> string(7) "current" ["a"]=> array(3) {
 ["href"]=> string(20) "http://habrahabr.ru/"
 ["class"]=> string(8) "disabled"
 ["#text"]=> string(10) "Посты" } }
*/ 
var_dump($saw->get('#sidebar dl.air-comment a.topic')->toArray());
/* На выходе: array(50) {
 [0]=> array(3) { ["class"]=> string(5) "topic"
 ["href"]=> string(36) "http://habrahabr.ru/blogs/os/110045/"
 ["#text"]=> string(63) "ФБР внедряло backdoor'ы в IPSec код OpenBSD (?)" } [1]=> array(3) { ["cl
*/
var_dump($saw->get('a[rel=bookmark]')->toArray());
/* На выходе: array(10) {
 [0]=> array(4) {
 ["rel"]=> string(8) "bookmark"
 ["href"]=> string(47) "http://habrahabr.ru/blogs/google_chrome/110099/"
 ["class"]=> string(5) "topic" ["#text"]=> string(100) "Google объявил Chrome готовым..." }
 [1]=> array(4) {
 ["rel"]=
*/

/**
 * Description of nokogiri
 *
 * @author olamedia
 */
class nokogiri implements IteratorAggregate{
    protected $_source = '';
    /**
     * @var DOMDocument
     */
    protected $_dom = null;
    /**
     * @var DOMXpath
     * */
    protected $_xpath = null;
    public function __construct($htmlString = ''){
        $this->loadHtml($htmlString);
    }
    public static function fromHtml($htmlString){
        $me = new self();
        $me->loadHtml($htmlString);
        return $me;
    }
    public static function fromDom($dom){
        $me = new self();
        $me->loadDom($dom);
        return $me;
    }
    public function loadDom($dom){
        $this->_dom = $dom;
        $this->_xpath = new DOMXpath($this->_dom);
    }
    public function loadHtml($htmlString = ''){
        $dom = new DOMDocument('1.0', 'UTF-8');
        $dom->preserveWhiteSpace = false;
        if (strlen($htmlString)){
            libxml_use_internal_errors(TRUE);
            $dom->loadHTML($htmlString);
            libxml_clear_errors();
        }
        $this->loadDom($dom);
    }
    function __invoke($expression){
        return $this->get($expression);
    }
    public function get($expression){
        if (strpos($expression, ' ') !== false){
            $a = explode(' ', $expression);
            foreach ($a as $k => $sub){
                $a[$k] = $this->getXpathSubquery($sub);
            }
            return $this->getElements(implode('', $a));
        }
        return $this->getElements($this->getXpathSubquery($expression));
    }
    protected function getXpathSubquery($expression){
        $query = '';
        if (preg_match("/(?P<tag>[a-z0-9]+)?
                        (\[(?P<attr>\S+)=(?P<value>\S+)\])?
                        (#(?P<id>\S+))?
                        (\.(?P<class>\S+))?/ims", $expression, $subs)){
            $tag = $subs['tag'];
            $id = $subs['id'];
            $attr = $subs['attr'];
            $attrValue = $subs['value'];
            $class = $subs['class'];
            if (!strlen($tag))
                $tag = '*';
            $query = '//'.$tag;
            if (strlen($id)){
                $query .= "[@id='".$id."']";
            }
            if (strlen($attr)){
                $query .= "[@".$attr."='".$attrValue."']";
            }
            if (strlen($class)){
                //$query .= "[@class='".$class."']";
                $query .= '[contains(concat(" ", normalize-space(@class), " "), " '.$class.' ")]';
            }
        }
        return $query;
    }
    protected function getElements($xpathQuery){
        $newDom = new DOMDocument('1.0', 'UTF-8');
        $root = $newDom->createElement('root');
        $newDom->appendChild($root);
        if (strlen($xpathQuery)){
            $nodeList = $this->_xpath->query($xpathQuery);
            if ($nodeList === false){
                throw new Exception('Malformed xpath');
            }
            foreach ($nodeList as $domElement){
                $domNode = $newDom->importNode($domElement, true);
                $root->appendChild($domNode);
            }
            return self::fromDom($newDom);
        }
    }
    public function toXml(){
        return $this->_dom->saveXML();
    }
    public function toArray($xnode = null){
        $array = array();
        if ($xnode === null){
            $node = $this->_dom;
        }else{
            $node = $xnode;
        }
        if ($node->nodeType == XML_TEXT_NODE){
            return $node->nodeValue;
        }
        if ($node->hasAttributes()){
            foreach ($node->attributes as $attr){
                $array[$attr->nodeName] = $attr->nodeValue;
            }
        }
        if ($node->hasChildNodes()){
            if ($node->childNodes->length == 1){
                $array[$node->firstChild->nodeName] = $this->toArray($node->firstChild);
            }else{
                foreach ($node->childNodes as $childNode){
                    if ($childNode->nodeType != XML_TEXT_NODE){
                        $array[$childNode->nodeName][] = $this->toArray($childNode);
                    }
                }
            }
        }
        if ($xnode === null){
            return reset(reset($array)); // first child
        }
        return $array;
    }
    public function getIterator(){
        $a = $this->toArray();
        return new ArrayIterator($a);
    }
}
Ошибки html игнорируются.
Распознаются вложеные теги (через пробел), а также конструкции вида .class, #id и [attr=value]
Создание из строки: nokogiri::fromString($htmlString); или new nokogiri($htmlString);
Создание из DomDocument: nokogiri::fromDom($dom);

Требования:
DOM, libxml, php 5.3 (вероятно работает и со многими старыми версиями)
HTML на входе должен быть в кодировке UTF-8
Код - пример #1
1
2
3
foreach ($saw->get('#sidebar a.topic') as $link){
    var_dump($link['#text']);
}
Предыдущие версии можно найти здесь. Скопипастил с хабра

среда, 18 августа 2010 г.

Парсинг HTML, DOM

Свое знакомство с php я начал именно с парсинга, в дальнейшем для облегчения я попробовал использовать Simple HTML DOM Parser. С ним работать очень удобно, но он жрет очень много памяти, и там где происходит много итераций с его участием скрипт завершает свою работу с Fatal error из за не хватки памяти.
 
Вообщем нашел я ему замену, регулярка которая парсит содержимое элемента по указному id или class-у.
Код - пример #1
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
class ParsDom {

    public $sContent = '';
    
    public function getElement($sId = '', $sElem = 'div') {
        if (!$sId || !$this->sContent) return '';
        $aOut[0] = array();
        $sReg = "
        /
        <{$sElem}[^>]+\b(?:class|id)=[\"\']?{$sId}[\"\']?[^>]*>
         (?:
           (<{$sElem}[^>]*>*?<\/{$sElem}>)|
           .
         )*?
        <\/{$sElem}>
        /xsS";

        preg_match_all($sReg, $this->sContent, $aOut);

        if (isset($aOut[0]))
            return $aOut[0];
        else    
            return '';
    }
}

// Пример
$oParsDom = new ParsDom;

// Контент от куда будем парсить
$oParsDom->sContent = $sData;

// Парсим все DIV элементы с указаным id или классом
$aDiv = $oParsDom->getElement('class_or_id_name');

// Парсим все LI элементы с указаным id или классом
$aLi = $oParsDom->getElement('menu', 'li');