1Parser(3)             User Contributed Perl Documentation            Parser(3)
2
3
4

NAME

6       HTML::Parser - HTML parser class
7

SYNOPSIS

9        use HTML::Parser ();
10
11        # Create parser object
12        $p = HTML::Parser->new( api_version => 3,
13                                start_h => [\&start, "tagname, attr"],
14                                end_h   => [\&end,   "tagname"],
15                                marked_sections => 1,
16                              );
17
18        # Parse document text chunk by chunk
19        $p->parse($chunk1);
20        $p->parse($chunk2);
21        #...
22        $p->eof;                 # signal end of document
23
24        # Parse directly from file
25        $p->parse_file("foo.html");
26        # or
27        open(my $fh, "<:utf8", "foo.html") ⎪⎪ die;
28        $p->parse_file($fh);
29

DESCRIPTION

31       Objects of the "HTML::Parser" class will recognize markup and separate
32       it from plain text (alias data content) in HTML documents.  As differ‐
33       ent kinds of markup and text are recognized, the corresponding event
34       handlers are invoked.
35
36       "HTML::Parser" is not a generic SGML parser.  We have tried to make it
37       able to deal with the HTML that is actually "out there", and it nor‐
38       mally parses as closely as possible to the way the popular web browsers
39       do it instead of strictly following one of the many HTML specifications
40       from W3C.  Where there is disagreement, there is often an option that
41       you can enable to get the official behaviour.
42
43       The document to be parsed may be supplied in arbitrary chunks.  This
44       makes on-the-fly parsing as documents are received from the network
45       possible.
46
47       If event driven parsing does not feel right for your application, you
48       might want to use "HTML::PullParser".  This is an "HTML::Parser" sub‐
49       class that allows a more conventional program structure.
50

METHODS

52       The following method is used to construct a new "HTML::Parser" object:
53
54       $p = HTML::Parser->new( %options_and_handlers )
55           This class method creates a new "HTML::Parser" object and returns
56           it.  Key/value argument pairs may be provided to assign event han‐
57           dlers or initialize parser options.  The handlers and parser
58           options can also be set or modified later by the method calls
59           described below.
60
61           If a top level key is in the form "<event>_h" (e.g., "text_h") then
62           it assigns a handler to that event, otherwise it initializes a
63           parser option. The event handler specification value must be an
64           array reference.  Multiple handlers may also be assigned with the
65           'handlers => [%handlers]' option.  See examples below.
66
67           If new() is called without any arguments, it will create a parser
68           that uses callback methods compatible with version 2 of
69           "HTML::Parser".  See the section on "version 2 compatibility" below
70           for details.
71
72           The special constructor option 'api_version => 2' can be used to
73           initialize version 2 callbacks while still setting other options
74           and handlers.  The 'api_version => 3' option can be used if you
75           don't want to set any options and don't want to fall back to v2
76           compatible mode.
77
78           Examples:
79
80            $p = HTML::Parser->new(api_version => 3,
81                                   text_h => [ sub {...}, "dtext" ]);
82
83           This creates a new parser object with a text event handler subrou‐
84           tine that receives the original text with general entities decoded.
85
86            $p = HTML::Parser->new(api_version => 3,
87                                   start_h => [ 'my_start', "self,tokens" ]);
88
89           This creates a new parser object with a start event handler method
90           that receives the $p and the tokens array.
91
92            $p = HTML::Parser->new(api_version => 3,
93                                   handlers => { text => [\@array, "event,text"],
94                                                 comment => [\@array, "event,text"],
95                                               });
96
97           This creates a new parser object that stores the event type and the
98           original text in @array for text and comment events.
99
100       The following methods feed the HTML document to the "HTML::Parser"
101       object:
102
103       $p->parse( $string )
104           Parse $string as the next chunk of the HTML document.  The return
105           value is normally a reference to the parser object (i.e. $p).  Han‐
106           dlers invoked should not attempt to modify the $string in-place
107           until $p->parse returns.
108
109           If an invoked event handler aborts parsing by calling $p->eof, then
110           $p->parse() will return a FALSE value.
111
112       $p->parse( $code_ref )
113           If a code reference is passed as the argument to be parsed, then
114           the chunks to be parsed are obtained by invoking this function
115           repeatedly.  Parsing continues until the function returns an empty
116           (or undefined) result.  When this happens $p->eof is automatically
117           signaled.
118
119           Parsing will also abort if one of the event handlers calls $p->eof.
120
121           The effect of this is the same as:
122
123            while (1) {
124               my $chunk = &$code_ref();
125               if (!defined($chunk) ⎪⎪ !length($chunk)) {
126                   $p->eof;
127                   return $p;
128               }
129               $p->parse($chunk) ⎪⎪ return undef;
130            }
131
132           But it is more efficient as this loop runs internally in XS code.
133
134       $p->parse_file( $file )
135           Parse text directly from a file.  The $file argument can be a file‐
136           name, an open file handle, or a reference to an open file handle.
137
138           If $file contains a filename and the file can't be opened, then the
139           method returns an undefined value and $! tells why it failed.  Oth‐
140           erwise the return value is a reference to the parser object.
141
142           If a file handle is passed as the $file argument, then the file
143           will normally be read until EOF, but not closed.
144
145           If an invoked event handler aborts parsing by calling $p->eof, then
146           $p->parse_file() may not have read the entire file.
147
148           On systems with multi-byte line terminators, the values passed for
149           the offset and length argspecs may be too low if parse_file() is
150           called on a file handle that is not in binary mode.
151
152           If a filename is passed in, then parse_file() will open the file in
153           binary mode.
154
155       $p->eof
156           Signals the end of the HTML document.  Calling the $p->eof method
157           outside a handler callback will flush any remaining buffered text
158           (which triggers the "text" event if there is any remaining text).
159
160           Calling $p->eof inside a handler will terminate parsing at that
161           point and cause $p->parse to return a FALSE value.  This also ter‐
162           minates parsing by $p->parse_file().
163
164           After $p->eof has been called, the parse() and parse_file() methods
165           can be invoked to feed new documents with the parser object.
166
167           The return value from eof() is a reference to the parser object.
168
169       Most parser options are controlled by boolean attributes.  Each boolean
170       attribute is enabled by calling the corresponding method with a TRUE
171       argument and disabled with a FALSE argument.  The attribute value is
172       left unchanged if no argument is given.  The return value from each
173       method is the old attribute value.
174
175       Methods that can be used to get and/or set parser options are:
176
177       $p->attr_encoded
178       $p->attr_encoded( $bool )
179           By default, the "attr" and @attr argspecs will have general enti‐
180           ties for attribute values decoded.  Enabling this attribute leaves
181           entities alone.
182
183       $p->boolean_attribute_value( $val )
184           This method sets the value reported for boolean attributes inside
185           HTML start tags.  By default, the name of the attribute is also
186           used as its value.  This affects the values reported for "tokens"
187           and "attr" argspecs.
188
189       $p->case_sensitive
190       $p->case_sensitive( $bool )
191           By default, tagnames and attribute names are down-cased.  Enabling
192           this attribute leaves them as found in the HTML source document.
193
194       $p->closing_plaintext
195       $p->closing_plaintext( $bool )
196           By default, "plaintext" element can never be closed. Everything up
197           to the end of the document is parsed in CDATA mode.  This histori‐
198           cal behaviour is what at least MSIE does.  Enabling this attribute
199           makes closing "</plaintext>" tag effective and the parsing process
200           will resume after seeing this tag.  This emulates gecko-based
201           browsers.
202
203       $p->empty_element_tags
204       $p->empty_element_tags( $bool )
205           By default, empty element tags are not recognized as such and the
206           "/" before ">" is just treated like a normal name character (unless
207           "strict_names" is enabled).  Enabling this attribute make
208           "HTML::Parser" recognize these tags.
209
210           Empty element tags look like start tags, but end with the character
211           sequence "/>" instead of ">".  When recognized by "HTML::Parser"
212           they cause an artificial end event in addition to the start event.
213           The "text" for the artificial end event will be empty and the
214           "tokenpos" array will be undefined even though the the token array
215           will have one element containing the tag name.
216
217       $p->marked_sections
218       $p->marked_sections( $bool )
219           By default, section markings like <![CDATA[...]]> are treated like
220           ordinary text.  When this attribute is enabled section markings are
221           honoured.
222
223           There are currently no events associated with the marked section
224           markup, but the text can be returned as "skipped_text".
225
226       $p->strict_comment
227       $p->strict_comment( $bool )
228           By default, comments are terminated by the first occurrence of
229           "-->".  This is the behaviour of most popular browsers (like
230           Mozilla, Opera and MSIE), but it is not correct according to the
231           official HTML standard.  Officially, you need an even number of
232           "--" tokens before the closing ">" is recognized and there may not
233           be anything but whitespace between an even and an odd "--".
234
235           The official behaviour is enabled by enabling this attribute.
236
237           Enabling of 'strict_comment' also disables recognizing these forms
238           as comments:
239
240             </ comment>
241             <! comment>
242
243       $p->strict_end
244       $p->strict_end( $bool )
245           By default, attributes and other junk are allowed to be present on
246           end tags in a manner that emulates MSIE's behaviour.
247
248           The official behaviour is enabled with this attribute.  If enabled,
249           only whitespace is allowed between the tagname and the final ">".
250
251       $p->strict_names
252       $p->strict_names( $bool )
253           By default, almost anything is allowed in tag and attribute names.
254           This is the behaviour of most popular browsers and allows us to
255           parse some broken tags with invalid attribute values like:
256
257              <IMG SRC=newprevlstGr.gif ALT=[PREV LIST] BORDER=0>
258
259           By default, "LIST]" is parsed as a boolean attribute, not as part
260           of the ALT value as was clearly intended.  This is also what
261           Mozilla sees.
262
263           The official behaviour is enabled by enabling this attribute.  If
264           enabled, it will cause the tag above to be reported as text since
265           "LIST]" is not a legal attribute name.
266
267       $p->unbroken_text
268       $p->unbroken_text( $bool )
269           By default, blocks of text are given to the text handler as soon as
270           possible (but the parser takes care always to break text at a
271           boundary between whitespace and non-whitespace so single words and
272           entities can always be decoded safely).  This might create breaks
273           that make it hard to do transformations on the text. When this
274           attribute is enabled, blocks of text are always reported in one
275           piece.  This will delay the text event until the following
276           (non-text) event has been recognized by the parser.
277
278           Note that the "offset" argspec will give you the offset of the
279           first segment of text and "length" is the combined length of the
280           segments.  Since there might be ignored tags in between, these num‐
281           bers can't be used to directly index in the original document file.
282
283       $p->utf8_mode
284       $p->utf8_mode( $bool )
285           Enable this option when parsing raw undecoded UTF-8.  This tells
286           the parser that the entities expanded for strings reported by
287           "attr", @attr and "dtext" should be expanded as decoded UTF-8 so
288           they end up compatible with the surrounding text.
289
290           If "utf8_mode" is enabled then it is an error to pass strings con‐
291           taining characters with code above 255 to the parse() method, and
292           the parse() method will croak if you try.
293
294           Example: The Unicode character "\x{2665}" is "\xE2\x99\xA5" when
295           UTF-8 encoded.  The character can also be represented by the entity
296           "&hearts;" or "&#x2665".  If we feed the parser:
297
298             $p->parse("\xE2\x99\xA5&hearts;");
299
300           then "dtext" will be reported as "\xE2\x99\xA5\x{2665}" without
301           "utf8_mode" enabled, but as "\xE2\x99\xA5\xE2\x99\xA5" when
302           enabled.  The later string is what you want.
303
304           This option is only available with perl-5.8 or better.
305
306       $p->xml_mode
307       $p->xml_mode( $bool )
308           Enabling this attribute changes the parser to allow some XML con‐
309           structs.  This enables the behaviour controlled by individually by
310           the "case_sensitive", "empty_element_tags", "strict_names" and
311           "xml_pic" attributes and also suppresses special treatment of ele‐
312           ments that are parsed as CDATA for HTML.
313
314       $p->xml_pic
315       $p->xml_pic( $bool )
316           By default, processing instructions are terminated by ">". When
317           this attribute is enabled, processing instructions are terminated
318           by "?>" instead.
319
320       As markup and text is recognized, handlers are invoked.  The following
321       method is used to set up handlers for different events:
322
323       $p->handler( event => \&subroutine, $argspec )
324       $p->handler( event => $method_name, $argspec )
325       $p->handler( event => \@accum, $argspec )
326       $p->handler( event => "" );
327       $p->handler( event => undef );
328       $p->handler( event );
329           This method assigns a subroutine, method, or array to handle an
330           event.
331
332           Event is one of "text", "start", "end", "declaration", "comment",
333           "process", "start_document", "end_document" or "default".
334
335           The "\&subroutine" is a reference to a subroutine which is called
336           to handle the event.
337
338           The $method_name is the name of a method of $p which is called to
339           handle the event.
340
341           The @accum is an array that will hold the event information as
342           sub-arrays.
343
344           If the second argument is "", the event is ignored.  If it is
345           undef, the default handler is invoked for the event.
346
347           The $argspec is a string that describes the information to be
348           reported for the event.  Any requested information that does not
349           apply to a specific event is passed as "undef".  If argspec is
350           omitted, then it is left unchanged.
351
352           The return value from $p->handler is the old callback routine or a
353           reference to the accumulator array.
354
355           Any return values from handler callback routines/methods are always
356           ignored.  A handler callback can request parsing to be aborted by
357           invoking the $p->eof method.  A handler callback is not allowed to
358           invoke the $p->parse() or $p->parse_file() method.  An exception
359           will be raised if it tries.
360
361           Examples:
362
363               $p->handler(start =>  "start", 'self, attr, attrseq, text' );
364
365           This causes the "start" method of object $p to be called for
366           'start' events.  The callback signature is $p->start(\%attr,
367           \@attr_seq, $text).
368
369               $p->handler(start =>  \&start, 'attr, attrseq, text' );
370
371           This causes subroutine start() to be called for 'start' events.
372           The callback signature is start(\%attr, \@attr_seq, $text).
373
374               $p->handler(start =>  \@accum, '"S", attr, attrseq, text' );
375
376           This causes 'start' event information to be saved in @accum.  The
377           array elements will be ['S', \%attr, \@attr_seq, $text].
378
379              $p->handler(start => "");
380
381           This causes 'start' events to be ignored.  It also suppresses invo‐
382           cations of any default handler for start events.  It is in most
383           cases equivalent to $p->handler(start => sub {}), but is more effi‐
384           cient.  It is different from the empty-sub-handler in that
385           "skipped_text" is not reset by it.
386
387              $p->handler(start => undef);
388
389           This causes no handler to be associated with start events.  If
390           there is a default handler it will be invoked.
391
392       Filters based on tags can be set up to limit the number of events
393       reported.  The main bottleneck during parsing is often the huge number
394       of callbacks made from the parser.  Applying filters can improve per‐
395       formance significantly.
396
397       The following methods control filters:
398
399       $p->ignore_elements( @tags )
400           Both the "start" event and the "end" event as well as any events
401           that would be reported in between are suppressed.  The ignored ele‐
402           ments can contain nested occurrences of itself.  Example:
403
404              $p->ignore_elements(qw(script style));
405
406           The "script" and "style" tags will always nest properly since their
407           content is parsed in CDATA mode.  For most other tags "ignore_ele‐
408           ments" must be used with caution since HTML is often not well
409           formed.
410
411       $p->ignore_tags( @tags )
412           Any "start" and "end" events involving any of the tags given are
413           suppressed.  To reset the filter (i.e. don't suppress any "start"
414           and "end" events), call "ignore_tags" without an argument.
415
416       $p->report_tags( @tags )
417           Any "start" and "end" events involving any of the tags not given
418           are suppressed.  To reset the filter (i.e. report all "start" and
419           "end" events), call "report_tags" without an argument.
420
421       Internally, the system has two filter lists, one for "report_tags" and
422       one for "ignore_tags", and both filters are applied.  This effectively
423       gives "ignore_tags" precedence over "report_tags".
424
425       Examples:
426
427          $p->ignore_tags(qw(style));
428          $p->report_tags(qw(script style));
429
430       results in only "script" events being reported.
431
432       Argspec
433
434       Argspec is a string containing a comma-separated list that describes
435       the information reported by the event.  The following argspec identi‐
436       fier names can be used:
437
438       "attr"
439           Attr causes a reference to a hash of attribute name/value pairs to
440           be passed.
441
442           Boolean attributes' values are either the value set by $p->bool‐
443           ean_attribute_value, or the attribute name if no value has been set
444           by $p->boolean_attribute_value.
445
446           This passes undef except for "start" events.
447
448           Unless "xml_mode" or "case_sensitive" is enabled, the attribute
449           names are forced to lower case.
450
451           General entities are decoded in the attribute values and one layer
452           of matching quotes enclosing the attribute values is removed.
453
454           The Unicode character set is assumed for entity decoding.  With
455           Perl version 5.6 or earlier only the Latin-1 range is supported,
456           and entities for characters outside the range 0..255 are left
457           unchanged.
458
459       @attr
460           Basically the same as "attr", but keys and values are passed as
461           individual arguments and the original sequence of the attributes is
462           kept.  The parameters passed will be the same as the @attr calcu‐
463           lated here:
464
465              @attr = map { $_ => $attr->{$_} } @$attrseq;
466
467           assuming $attr and $attrseq here are the hash and array passed as
468           the result of "attr" and "attrseq" argspecs.
469
470           This passes no values for events besides "start".
471
472       "attrseq"
473           Attrseq causes a reference to an array of attribute names to be
474           passed.  This can be useful if you want to walk the "attr" hash in
475           the original sequence.
476
477           This passes undef except for "start" events.
478
479           Unless "xml_mode" or "case_sensitive" is enabled, the attribute
480           names are forced to lower case.
481
482       "column"
483           Column causes the column number of the start of the event to be
484           passed.  The first column on a line is 0.
485
486       "dtext"
487           Dtext causes the decoded text to be passed.  General entities are
488           automatically decoded unless the event was inside a CDATA section
489           or was between literal start and end tags ("script", "style",
490           "xmp", and "plaintext").
491
492           The Unicode character set is assumed for entity decoding.  With
493           Perl version 5.6 or earlier only the Latin-1 range is supported,
494           and entities for characters outside the range 0..255 are left
495           unchanged.
496
497           This passes undef except for "text" events.
498
499       "event"
500           Event causes the event name to be passed.
501
502           The event name is one of "text", "start", "end", "declaration",
503           "comment", "process", "start_document" or "end_document".
504
505       "is_cdata"
506           Is_cdata causes a TRUE value to be passed if the event is inside a
507           CDATA section or between literal start and end tags ("script",
508           "style", "xmp", and "plaintext").
509
510           if the flag is FALSE for a text event, then you should normally
511           either use "dtext" or decode the entities yourself before the text
512           is processed further.
513
514       "length"
515           Length causes the number of bytes of the source text of the event
516           to be passed.
517
518       "line"
519           Line causes the line number of the start of the event to be passed.
520           The first line in the document is 1.  Line counting doesn't start
521           until at least one handler requests this value to be reported.
522
523       "offset"
524           Offset causes the byte position in the HTML document of the start
525           of the event to be passed.  The first byte in the document has off‐
526           set 0.
527
528       "offset_end"
529           Offset_end causes the byte position in the HTML document of the end
530           of the event to be passed.  This is the same as "offset" +
531           "length".
532
533       "self"
534           Self causes the current object to be passed to the handler.  If the
535           handler is a method, this must be the first element in the argspec.
536
537           An alternative to passing self as an argspec is to register clo‐
538           sures that capture $self by themselves as handlers.  Unfortunately
539           this creates circular references which prevent the HTML::Parser
540           object from being garbage collected.  Using the "self" argspec
541           avoids this problem.
542
543       "skipped_text"
544           Skipped_text returns the concatenated text of all the events that
545           have been skipped since the last time an event was reported.
546           Events might be skipped because no handler is registered for them
547           or because some filter applies.  Skipped text also includes marked
548           section markup, since there are no events that can catch it.
549
550           If an ""-handler is registered for an event, then the text for this
551           event is not included in "skipped_text".  Skipped text both before
552           and after the ""-event is included in the next reported
553           "skipped_text".
554
555       "tag"
556           Same as "tagname", but prefixed with "/" if it belongs to an "end"
557           event and "!" for a declaration.  The "tag" does not have any pre‐
558           fix for "start" events, and is in this case identical to "tagname".
559
560       "tagname"
561           This is the element name (or generic identifier in SGML jargon) for
562           start and end tags.  Since HTML is case insensitive, this name is
563           forced to lower case to ease string matching.
564
565           Since XML is case sensitive, the tagname case is not changed when
566           "xml_mode" is enabled.  The same happens if the "case_sensitive"
567           attribute is set.
568
569           The declaration type of declaration elements is also passed as a
570           tagname, even if that is a bit strange.  In fact, in the current
571           implementation tagname is identical to "token0" except that the
572           name may be forced to lower case.
573
574       "token0"
575           Token0 causes the original text of the first token string to be
576           passed.  This should always be the same as $tokens->[0].
577
578           For "declaration" events, this is the declaration type.
579
580           For "start" and "end" events, this is the tag name.
581
582           For "process" and non-strict "comment" events, this is everything
583           inside the tag.
584
585           This passes undef if there are no tokens in the event.
586
587       "tokenpos"
588           Tokenpos causes a reference to an array of token positions to be
589           passed.  For each string that appears in "tokens", this array con‐
590           tains two numbers.  The first number is the offset of the start of
591           the token in the original "text" and the second number is the
592           length of the token.
593
594           Boolean attributes in a "start" event will have (0,0) for the
595           attribute value offset and length.
596
597           This passes undef if there are no tokens in the event (e.g.,
598           "text") and for artificial "end" events triggered by empty element
599           tags.
600
601           If you are using these offsets and lengths to modify "text", you
602           should either work from right to left, or be very careful to calcu‐
603           late the changes to the offsets.
604
605       "tokens"
606           Tokens causes a reference to an array of token strings to be
607           passed.  The strings are exactly as they were found in the original
608           text, no decoding or case changes are applied.
609
610           For "declaration" events, the array contains each word, comment,
611           and delimited string starting with the declaration type.
612
613           For "comment" events, this contains each sub-comment.  If
614           $p->strict_comments is disabled, there will be only one sub-com‐
615           ment.
616
617           For "start" events, this contains the original tag name followed by
618           the attribute name/value pairs.  The values of boolean attributes
619           will be either the value set by $p->boolean_attribute_value, or the
620           attribute name if no value has been set by $p->bool‐
621           ean_attribute_value.
622
623           For "end" events, this contains the original tag name (always one
624           token).
625
626           For "process" events, this contains the process instructions
627           (always one token).
628
629           This passes "undef" for "text" events.
630
631       "text"
632           Text causes the source text (including markup element delimiters)
633           to be passed.
634
635       "undef"
636           Pass an undefined value.  Useful as padding where the same handler
637           routine is registered for multiple events.
638
639       '...'
640           A literal string of 0 to 255 characters enclosed in single (') or
641           double (") quotes is passed as entered.
642
643       The whole argspec string can be wrapped up in '@{...}' to signal that
644       the resulting event array should be flattened.  This only makes a dif‐
645       ference if an array reference is used as the handler target.  Consider
646       this example:
647
648          $p->handler(text => [], 'text');
649          $p->handler(text => [], '@{text}']);
650
651       With two text events; "foo", "bar"; then the first example will end up
652       with [["foo"], ["bar"]] and the second with ["foo", "bar"] in the han‐
653       dler target array.
654
655       Events
656
657       Handlers for the following events can be registered:
658
659       "comment"
660           This event is triggered when a markup comment is recognized.
661
662           Example:
663
664             <!-- This is a comment -- -- So is this -->
665
666       "declaration"
667           This event is triggered when a markup declaration is recognized.
668
669           For typical HTML documents, the only declaration you are likely to
670           find is <!DOCTYPE ...>.
671
672           Example:
673
674             <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
675             "http://www.w3.org/TR/html40/strict.dtd">
676
677           DTDs inside <!DOCTYPE ...> will confuse HTML::Parser.
678
679       "default"
680           This event is triggered for events that do not have a specific han‐
681           dler.  You can set up a handler for this event to catch stuff you
682           did not want to catch explicitly.
683
684       "end"
685           This event is triggered when an end tag is recognized.
686
687           Example:
688
689             </A>
690
691       "end_document"
692           This event is triggered when $p->eof is called and after any
693           remaining text is flushed.  There is no document text associated
694           with this event.
695
696       "process"
697           This event is triggered when a processing instructions markup is
698           recognized.
699
700           The format and content of processing instructions are system and
701           application dependent.
702
703           Examples:
704
705             <? HTML processing instructions >
706             <? XML processing instructions ?>
707
708       "start"
709           This event is triggered when a start tag is recognized.
710
711           Example:
712
713             <A HREF="http://www.perl.com/">
714
715       "start_document"
716           This event is triggered before any other events for a new document.
717           A handler for it can be used to initialize stuff.  There is no doc‐
718           ument text associated with this event.
719
720       "text"
721           This event is triggered when plain text (characters) is recognized.
722           The text may contain multiple lines.  A sequence of text may be
723           broken between several text events unless $p->unbroken_text is
724           enabled.
725
726           The parser will make sure that it does not break a word or a
727           sequence of whitespace between two text events.
728
729       Unicode
730
731       The "HTML::Parser" can parse Unicode strings when running under
732       perl-5.8 or better.  If Unicode is passed to $p->parse() then chunks of
733       Unicode will be reported to the handlers.  The offset and length
734       argspecs will also report their position in terms of characters.
735
736       It is safe to parse raw undecoded UTF-8 if you either avoid decoding
737       entities and make sure to not use argspecs that do, or enable the
738       "utf8_mode" for the parser.  Parsing of undecoded UTF-8 might be useful
739       when parsing from a file where you need the reported offsets and
740       lengths to match the byte offsets in the file.
741
742       If a filename is passed to $p->parse_file() then the file will be read
743       in binary mode.  This will be fine if the file contains only ASCII or
744       Latin-1 characters.  If the file contains UTF-8 encoded text then care
745       must be taken when decoding entities as described in the previous para‐
746       graph, but better is to open the file with the UTF-8 layer so that it
747       is decoded properly:
748
749          open(my $fh, "<:utf8", "index.html") ⎪⎪ die "...: $!";
750          $p->parse_file($fh);
751
752       If the file contains text encoded in a charset besides ASCII, Latin-1
753       or UTF-8 then decoding will always be needed.
754

VERSION 2 COMPATIBILITY

756       When an "HTML::Parser" object is constructed with no arguments, a set
757       of handlers is automatically provided that is compatible with the old
758       HTML::Parser version 2 callback methods.
759
760       This is equivalent to the following method calls:
761
762          $p->handler(start   => "start",   "self, tagname, attr, attrseq, text");
763          $p->handler(end     => "end",     "self, tagname, text");
764          $p->handler(text    => "text",    "self, text, is_cdata");
765          $p->handler(process => "process", "self, token0, text");
766          $p->handler(comment =>
767                    sub {
768                        my($self, $tokens) = @_;
769                        for (@$tokens) {$self->comment($_);}},
770                    "self, tokens");
771          $p->handler(declaration =>
772                    sub {
773                        my $self = shift;
774                        $self->declaration(substr($_[0], 2, -1));},
775                    "self, text");
776
777       Setting up these handlers can also be requested with the "api_version
778       => 2" constructor option.
779

SUBCLASSING

781       The "HTML::Parser" class is subclassable.  Parser objects are plain
782       hashes and "HTML::Parser" reserves only hash keys that start with
783       "_hparser".  The parser state can be set up by invoking the init()
784       method, which takes the same arguments as new().
785

EXAMPLES

787       The first simple example shows how you might strip out comments from an
788       HTML document.  We achieve this by setting up a comment handler that
789       does nothing and a default handler that will print out anything else:
790
791         use HTML::Parser;
792         HTML::Parser->new(default_h => [sub { print shift }, 'text'],
793                           comment_h => [""],
794                          )->parse_file(shift ⎪⎪ die) ⎪⎪ die $!;
795
796       An alternative implementation is:
797
798         use HTML::Parser;
799         HTML::Parser->new(end_document_h => [sub { print shift },
800                                              'skipped_text'],
801                           comment_h      => [""],
802                          )->parse_file(shift ⎪⎪ die) ⎪⎪ die $!;
803
804       This will in most cases be much more efficient since only a single
805       callback will be made.
806
807       The next example prints out the text that is inside the <title> element
808       of an HTML document.  Here we start by setting up a start handler.
809       When it sees the title start tag it enables a text handler that prints
810       any text found and an end handler that will terminate parsing as soon
811       as the title end tag is seen:
812
813         use HTML::Parser ();
814
815         sub start_handler
816         {
817           return if shift ne "title";
818           my $self = shift;
819           $self->handler(text => sub { print shift }, "dtext");
820           $self->handler(end  => sub { shift->eof if shift eq "title"; },
821                                  "tagname,self");
822         }
823
824         my $p = HTML::Parser->new(api_version => 3);
825         $p->handler( start => \&start_handler, "tagname,self");
826         $p->parse_file(shift ⎪⎪ die) ⎪⎪ die $!;
827         print "\n";
828
829       More examples are found in the eg/ directory of the "HTML-Parser" dis‐
830       tribution: the program "hrefsub" shows how you can edit all links found
831       in a document; the program "htextsub" shows how to edit the text only;
832       the program "hstrip" shows how you can strip out certain tags/elements
833       and/or attributes; and the program "htext" show how to obtain the plain
834       text, but not any script/style content.
835
836       You can browse the eg/ directory online from the [Browse] link on the
837       http://search.cpan.org/~gaas/HTML-Parser/ page.
838

BUGS

840       The <style> and <script> sections do not end with the first "</", but
841       need the complete corresponding end tag.  The standard behaviour is not
842       really practical.
843
844       When the strict_comment option is enabled, we still recognize comments
845       where there is something other than whitespace between even and odd
846       "--" markers.
847
848       Once $p->boolean_attribute_value has been set, there is no way to
849       restore the default behaviour.
850
851       There is currently no way to get both quote characters into the same
852       literal argspec.
853
854       Empty tags, e.g. "<>" and "</>", are not recognized.  SGML allows them
855       to repeat the previous start tag or close the previous start tag
856       respectively.
857
858       NET tags, e.g. "code/.../" are not recognized.  This is SGML shorthand
859       for "<code>...</code>".
860
861       Unclosed start or end tags, e.g. "<tt<b>...</b</tt>" are not recog‐
862       nized.
863

DIAGNOSTICS

865       The following messages may be produced by HTML::Parser.  The notation
866       in this listing is the same as used in perldiag:
867
868       Not a reference to a hash
869           (F) The object blessed into or subclassed from HTML::Parser is not
870           a hash as required by the HTML::Parser methods.
871
872       Bad signature in parser state object at %p
873           (F) The _hparser_xs_state element does not refer to a valid state
874           structure.  Something must have changed the internal value stored
875           in this hash element, or the memory has been overwritten.
876
877       _hparser_xs_state element is not a reference
878           (F) The _hparser_xs_state element has been destroyed.
879
880       Can't find '_hparser_xs_state' element in HTML::Parser hash
881           (F) The _hparser_xs_state element is missing from the parser hash.
882           It was either deleted, or not created when the object was created.
883
884       API version %s not supported by HTML::Parser %s
885           (F) The constructor option 'api_version' with an argument greater
886           than or equal to 4 is reserved for future extensions.
887
888       Bad constructor option '%s'
889           (F) An unknown constructor option key was passed to the new() or
890           init() methods.
891
892       Parse loop not allowed
893           (F) A handler invoked the parse() or parse_file() method.  This is
894           not permitted.
895
896       marked sections not supported
897           (F) The $p->marked_sections() method was invoked in a HTML::Parser
898           module that was compiled without support for marked sections.
899
900       Unknown boolean attribute (%d)
901           (F) Something is wrong with the internal logic that set up aliases
902           for boolean attributes.
903
904       Only code or array references allowed as handler
905           (F) The second argument for $p->handler must be either a subroutine
906           reference, then name of a subroutine or method, or a reference to
907           an array.
908
909       No handler for %s events
910           (F) The first argument to $p->handler must be a valid event name;
911           i.e. one of "start", "end", "text", "process", "declaration" or
912           "comment".
913
914       Unrecognized identifier %s in argspec
915           (F) The identifier is not a known argspec name.  Use one of the
916           names mentioned in the argspec section above.
917
918       Literal string is longer than 255 chars in argspec
919           (F) The current implementation limits the length of literals in an
920           argspec to 255 characters.  Make the literal shorter.
921
922       Backslash reserved for literal string in argspec
923           (F) The backslash character "\" is not allowed in argspec literals.
924           It is reserved to permit quoting inside a literal in a later ver‐
925           sion.
926
927       Unterminated literal string in argspec
928           (F) The terminating quote character for a literal was not found.
929
930       Bad argspec (%s)
931           (F) Only identifier names, literals, spaces and commas are allowed
932           in argspecs.
933
934       Missing comma separator in argspec
935           (F) Identifiers in an argspec must be separated with ",".
936
937       Parsing of undecoded UTF-8 will give garbage when decoding entities
938           (W) The first chunk parsed appears to contain undecoded UTF-8 and
939           one or more argspecs that decode entities are used for the callback
940           handlers.
941
942           The result of decoding will be a mix of encoded and decoded charac‐
943           ters for any entities that expand to characters with code above
944           127.  This is not a good thing.
945
946           The solution is to use the Encode::encode_utf8() on the data before
947           feeding it to the $p->parse().  For $p->parse_file() pass a file
948           that has been opened in ":utf8" mode.
949
950           The parser can process raw undecoded UTF-8 sanely if the
951           "utf8_mode" is enabled or if the "attr", "@attr" or "dtext"
952           argspecs is avoided.
953
954       Parsing string decoded with wrong endianess
955           (W) The first character in the document is U+FFFE.  This is not a
956           legal Unicode character but a byte swapped BOM.  The result of
957           parsing will likely be garbage.
958
959       Parsing of undecoded UTF-32
960           (W) The parser found the Unicode UTF-32 BOM signature at the start
961           of the document.  The result of parsing will likely be garbage.
962
963       Parsing of undecoded UTF-16
964           (W) The parser found the Unicode UTF-16 BOM signature at the start
965           of the document.  The result of parsing will likely be garbage.
966

SEE ALSO

968       HTML::Entities, HTML::PullParser, HTML::TokeParser, HTML::HeadParser,
969       HTML::LinkExtor, HTML::Form
970
971       HTML::TreeBuilder (part of the HTML-Tree distribution)
972
973       http://www.w3.org/TR/html4
974
975       More information about marked sections and processing instructions may
976       be found at "http://www.sgml.u-net.com/book/sgml-8.htm".
977
979        Copyright 1996-2007 Gisle Aas. All rights reserved.
980        Copyright 1999-2000 Michael A. Chase.  All rights reserved.
981
982       This library is free software; you can redistribute it and/or modify it
983       under the same terms as Perl itself.
984
985
986
987perl v5.8.8                       2006-04-26                         Parser(3)
Impressum