How To Make A Parser

Table of contents:

How To Make A Parser
How To Make A Parser

Video: How To Make A Parser

Video: How To Make A Parser
Video: Building a Parser from scratch. Lecture [1/18]: Tokenizer | Parser 2024, November
Anonim

Parsing is one of the widely used techniques in web page programming. It easily and simply allows you to get the necessary service to the site using a small number of commands, when there is no way to write the necessary script yourself.

How to make a parser
How to make a parser

Instructions

Step 1

The easiest way to parse is with the PHP function file_get_contents (). It allows you to get the contents of a file as a text string. The function uses the "memory mapping" algorithm, which improves its performance.

Step 2

For example, to write a script that parses data from a website of the Central Bank of the Russian Federation, you need to get the content of an XML page using the appropriate function, having previously defined the date in the format appropriate for the site, and then using regular expressions to split it. To display the selected currency, the code obtained from the Bank's website is used: $ data = date (“d / m / Y”); $ get = file_get_contents (https://www.cbr.ru/scripts/XML_daily.asp?date_req=$ data); preg_match (“/(.*?)/ is”, $ get, $ string); preg_match (“/(.*?)/ is”, $ string [1], $ str);

Step 3

If you want to parse the XML file itself, there are also corresponding functions for this. To start the parser, you need to initialize it using xml_parser_create: $ parser = xml_parser_create ();

Step 4

Then a list of functions is specified that will process the corresponding tags and text information. The appropriate XML element start and end handlers are set: xml_set_element_handler ($ parser, “startElement”, “endElement”);

Step 5

Data can be read using the standard fopen () and fgets () functions within the appropriate loop. The contents of the files are returned line by line in xml_parse (). The last parameter contains the flag of reading the last line: while ($ content = fgets ($ fparse)) {

if (! xml_parse ($ parser, $ content, feof ($ fparse))) {

echo “Error”;

break; }}

Step 6

The xml_parser_free () function is used to free the resources occupied by the system. These functions are most powerful when processing XML files.

Recommended: