PHP mining XML and HTML data mining and its importance
Common Acronyms
API: application programming interface CDATA: Character data DOM: Document object mode FTP: file transfer protocol HTML: Hypertext Markup Language HTTP: Hypertext Transfer Protocol REST: concrete state transmission URL: unified Resource Locator W3C: World Wide Web Alliance XML: Extensible Markup Language
Wikipedia defines "data mining" as "data mining is a process that uses statistical and artificial intelligence methods, combined with database management, to extract models from large datasets ". This is a very in-depth definition and may exceed the typical use cases of most people. Few people use artificial intelligence. generally, data mining only searches for and aggregates large datasets to find useful information.
With the rapid development of the Internet and the provision of massive information, it is very important to collect large amounts of data and make the data meaningful. It is important to collect large datasets that individuals cannot read and extract them into useful data. This type of data mining is the focus of this article, this article will specifically introduce how to collect and parse such data.
Back to top
Practical application of data mining
Data mining has many practical applications. You may assume that you want to search for a website and find the information provided (such as attendance records for movies or concerts ). You may need to retrieve more serious information, such as voter records and obtain useful data. Or, more often, you may need to check the social network data and try to parse the data to understand a certain trend, such as the frequency at which your company is mentioned, and whether this mention is positive or negative.
Back to top
Precautions before mining websites
Before proceeding to the following content, we assume that you will extract data from another website. If you already have the data to be processed, it is completely different. When you extract data from a website, make sure that you comply with the terms of service, whether you are performing a Web erasure (which will be detailed later) or using an API. If you are performing an erasure, you also need to observe the robots.txt file of the site. this file describes what parts of the website scripts are allowed to access. Finally, make sure that the site bandwidth is not blocked. The script you write cannot access the site data as quickly as the script can run. Otherwise, this may not only cause hosting problems, but may also face the risk of being banned or blocked because the script is too "aggressive.
Back to top
Understanding XML data structure
Whatever method you use to extract data, you may receive data in XML (or HTML) format. When XML supports data sharing, XML becomes the standard language for Internet. Before considering how to extract data, it is important to study the XML structure and how to process XML data.
The basic structure of XML documents is very intuitive, especially when you have used HTML before. All data in the XML document is stored in either of the two methods. The primary way to store data is to store the data in the nested tag. The following is a simple example. if you have an address, the data can be stored in the document as follows:
1234 Main Street, Baltimore, MD |
You can nest these XML data points to create a list of multiple addresses. You can put all these addresses in another tag and mark them as locations in this example (see listing 1 ).
Listing 1. multiple addresses in XML
1234 Main Street, Baltimore, MD 567 1st Street, San Jose, CA 901 Washington Ave, Chicago, IL
|
To further expand this method, these addresses can be divided into various components: streets, cities, and states, making data processing easier. In this way, the generated XML file is more typical, as shown in listing 2.
Listing 2. completely decomposed addresses in XML
1234 Main Street
Baltimore
MD
567 1st Street
San Jose
CA
901 Washington Ave
Chicago
IL
|
As mentioned above, there are two ways to store XML data, one of which we have seen just now. Another method is to store data through attributes. You can assign several attributes to each tag. Although this method is less commonly used, it may be a very useful tool. Sometimes, it provides additional information, such as a unique ID or an event date. A more common case is to add metadata. in your address example, you can use the type attribute to indicate whether the address is a home address or a work address, as shown in listing 3.
Listing 3. markup added to XML
1234 Main Street
Baltimore
MD
567 1st Street
San Jose
CA
901 Washington Ave
Chicago
IL
|
Note: XML documents always have a parent-level root tag/node. All other tags/nodes are child-level tags/nodes of the root tag/node. The beginning of an XML document can contain other statements and definitions, as well as other complex content (such as CDATA blocks ). We strongly recommend that you refer to references for more information about XML.
Back to top
Parse XML data in PHP
You have learned about the XML appearance and structure. now let's look at how to parse and programmatically access XML data in PHP. Several libraries created for PHP allow XML parsing. each database has its advantages and disadvantages. These libraries include DOM, XMLReader/Writer, XML Parser, and SimpleXML. For the purpose of this article, we mainly focus on SimpleXML, because it is one of the most common libraries and one of my favorite libraries.
SimpleXML, as its name implies, aims to provide a very simple interface to access XML. It can convert an XML document to an internal PHP object format. The vertex data point becomes as simple as the access object variable. To use SimpleXML to parse an XML document, you only need to use the simplexml_load_file () function (see listing 4 ).
Listing 4. use SimpleXML to parse the document
That's easy! But please note that, thanks to PHP's file stream integration, you can insert a file name or URL here, and file stream integration will automatically retrieve it. If the XML file has been loaded into the memory, you can also use simplexml_load_string (). If you run this code in XML in listing 3 and use print_r () to view the approximate structure of the data, you will get the output shown in listing 5.
Listing 5. parsed XML output
SimpleXMLElement Object ( [address] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [type] => home ) [street] => 1234 Main Street [city] => Baltimore [state] => MD ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [type] => work ) [street] => 567 1st Street [city] => San Jose [state] => CA ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [type] => work ) [street] => 901 Washington Ave [city] => Chicago [state] => IL ) )) |
Then, you can access data using standard PHP Objects and methods. For example, to display each state that someone lives in, you can use iterative addresses (see listing 6 ).
Listing 6. iteration address
address as $address) { echo $address->state, " \n";}?> |
The access attributes are slightly different. Different from the referenced object property, you can access the property as an array value. You can change the code sample above to display the type attribute. you can use the code shown in listing 7 to perform the preceding operations.
Listing 7. Adding attributes
address as $address) { echo $address->state, ': ', $address['type'], " \n";}?> |
Although all the examples above involve iterations, you can directly access the data and use the specific information snippets you need. for example, extract the street address of the second address through the following code: $ xml-> address [1]-> street.
Now, you should have some basic tools to start processing XML data. For more information, see the SimpleXML document and other links listed in references.
Back to top
Data Mining in PHP: Possible methods
As mentioned above, you can access data in multiple ways. The two main methods are Web erasure and API usage.
Web erasure
Scraping downloads all Web pages programmatically and extracts data from them. Many books have devoted themselves to this topic (see references ). I will only list some tools required for Web erasure. First, PHP makes it easy to read a Web page into a string. There are many ways to complete this task, including using file_get_contents () through a URL, but here you want to parse HTML in a meaningful way.
Because HTML is essentially an XML-based language, it is useful to convert HTML into a SimpleXML structure. However, you cannot just use simplexml_load_file () to load HTML pages, because even valid HTML is still not XML. A good solution is to use DOM extensions to load HTML pages as DOM documents and convert them to SimpleXML, as shown in listing 8.
Listing 8. use the DOM method to obtain the SimpleXML version of the Web page
loadHTMLFile('http://example.com/');$xml = simplexml_import_dom($dom);?> |
Now, you can traverse HTML pages like other XML documents. Therefore, you can use $ xml-> head-> title to access the page title, you can also use a reference such as $ xml-> body-> p [0]-> p [0]-> h4 [0] to go deep into the page.
However, as you can expect from the previous example, it may be inconvenient to try to find data from an HTML page, this is because HTML pages are generally not as well structured as XML files. The above line of code looks for the first h4 in three nested p; in each case, it looks for the first p in each parent p.
Fortunately, if you only want to find the first h4 on the page or other "direct data", XPath is a simpler implementation method. XPath is a very powerful tool that can be used as the topic of the entire article series (see some articles listed in references ). In short, you can use '/' to describe hierarchical relationships. Therefore, you can rewrite the previous reference to the following XPath search (see listing 9 ).
Listing 9. using XPath directly
xpath('/html/body/p/p/p/h4');?> |
Alternatively, you can only use the '//' option and XPath, which searches all documents for the tags you want to search. Therefore, you can find all h4, generate an array, and then use the following XPath to access the first h4:
'// H4'
Traverse HTML hierarchies
The main reason for discussing the above conversions and XPath is that one of the common necessary tasks for Web erasure is to automatically search for other links on the Web page and trace them, which allows you to "traverse" the website, find as much information as possible.
If you use XPath, this task will be very troublesome. Listing 10 provides an array consisting of all links with the "href" attribute and allows you to process them.
Listing 10. searching all links on the page using multiple technologies
loadHTMLFile('http://example.com/');$xml = simplexml_import_dom($dom);$links = $xml->xpath('//a[@href]');foreach ($links as $l) { echo $l['href'], " \n";}?> |
Now, all the links are found in the above code, but if you open every possible link you find, you can quickly "crawl" the entire Web. Therefore, it is best to enhance your code to ensure that only two types of links are Accessed: one is a valid HTML link (not an FTP or JavaScript link), and the other is to return only (through the complete or relative domain link) the link of the same website.
A simpler method is to use the PHP built-in parse_url () function to iterate over these links. this function handles a large number of qualification checks for you, as shown in listing 11.
Listing 11. a more robust website traversal program
loadHTMLFile("http://{$host}/");$xml = simplexml_import_dom($dom);$links = $xml->xpath('//a[@href]');foreach ($links as $l) { $p = parse_url($l['href']); if (empty($p['scheme']) || in_array($p['scheme'], array('http', 'https'))) { if (empty($p['host']) || ($host == $p['host'])) { echo $l['href'], " \n"; // Handle URL iteration here } }}?> |
The last note about HTML parsing is that for a unified interface for all XML classes, you have reviewed how to convert HTML back to SimpleXML by using only DOM extensions. Note that the DOM library is very powerful and can be used directly. If you are familiar with JavaScript and use tools such as getElementsByTagName to traverse the DOM document tree, you can use only the DOM library instead of SimpleXML.
You already have the tools required to erase data from the Web page. Once you are familiar with the technology described above, you can read any information from the Web page, not just links that can be followed. We hope that you do not need to execute this task because an API or another data source already exists.
Use XML APIs and data
Now you have mastered some basic skills to access and use the main XML data APIs on the Internet. They are generally based on REST, so you only need a simple HTTP access to retrieve the data, and use the end of the previous introduction to parse the data.
Each API performs differently in this respect. We cannot describe how to access each API one by one. Therefore, we will only briefly introduce some basic xml api examples. An RSS feed is the most common data source that uses XML format. RSS stands for Really Simple Syndication, which is usually a standard format used to share frequently updated data, such as blog posts, news titles, or podcasts. For details about the RSS format, see references. Note that RSS is an XML file named Parent tag, which has several Tag. each tag provides a set of data points.
The following is an example. Suppose we use SimpleXML to read the RSS feed of the New York Times title (see references for a link to this RSS feed) and format a column of title, the headers are linked to the corresponding body (see listing 12 ).
Listing 12. reading RSS feed from the New York Times
channel->item as $item) { echo "
- link}\">{$item->title}
";}?>
|
Figure 1 shows the output from the New York Times summary.
Output from the New York Times summary
Now, let's explore a more fully functional REST-based API. The Flickr API is a good starting point because it provides a large amount of data but does not require authentication. Many APIs require authentication (using Oauth or other mechanisms) to operate on behalf of a Web user. This step can be applied to the entire API or only some APIs. See each API document to learn how to perform authentication.
To learn how to use the Flickr API for an unauthenticated request, you can use its search API. As an example, we search for all the public cross bows in Flickr. Although authentication is not required, like many APIs, an API key must be generated for data access. For more information about how to complete this task, see the API documentation of Flickr. With an API key, you can use the search function of the Flickr API for exploration, as shown in listing 13.
Listing 13. search for "crossbow" using the Flickr API"
'flickr.photos.search', 'api_key' => $key, 'text' => 'crossbow', // Our search term 'media' => 'photos', 'per_page' => 20 // We only want 20 results);// Now make the request to Flickr:$xml = simplexml_load_file($apiurl . http_build_query($params));// From this, iterate over the list of photos & request more info:foreach ($xml->photos->photo as $photo) { // Build a new request with this photo's ID $params = array( 'method' => 'flickr.photos.getInfo', 'api_key' => $key, 'photo_id' => (string)$photo['id'] ); $info = simplexml_load_file($apiurl . http_build_query($params)); // Now $info holds a vast amount of data about the image including // owner, GPS, dates, description, tags, etc ... all to be used. // Let's also request "sizes" to get all of the image URLs: $params = array( 'method' => 'flickr.photos.getSizes', 'api_key' => $key, 'photo_id' => (string)$photo['id'] ); $sizes = simplexml_load_file($apiurl . http_build_query($params)); $small = $sizes->xpath("//size[@label='Small']"); // For now, just going to create a simple display of the image, // linked back to Flickr, with title, GPS info, and more shown: echo <<
photo->urls->url[0]}">
- Title: {$info->photo->title}
- User: {$info->photo->owner['realname']}
- Date Taken: {$info->photo->dates['taken']}
- Location: {$info->photo->location->locality}, {$info->photo->location->county}, {$info->photo->location->region}, {$info->photo->location->country}
EOHTML;}?>
|
Figure 2 shows the output of the Flickr program. Your Cross bow search results include some photos and related information about each photo (title, user, location, and photography date ).
Figure 2. Sample output from the Flickr program in listing 13
You have seen how powerful such an API is and how to obtain the required data in conjunction with various calls in the same API. With these basic technologies, you can mine data from any website or information source.
Consider how to obtain programming access to data through an API or Web erasure. Then, use the displayed method to access and iterate all target data.
Back to top
Store and report extracted data
Finally, storage and report data are the easiest and most interesting in many aspects. You can use your imagination whenever you decide how to handle this problem based on your actual situation.
Typically, you obtain all the data you collect and store it in a database. Then, design your data structure so that it matches the way you plan to access data in the future. In this case, store as much information as possible and may be used in the future. Although data can always be deleted, retrieving additional information may be a painful process once there is too much data. But it is better to store more data at the beginning. after all, you will never know which data may be useful.
After storing data in a database or similar data storage, you can create a report. Creating a report may be simple. you only need to run several basic SQL queries on the database to view the number of times a data appears. Alternatively, creating a report may be a very complex Web user interface, it is designed to allow users to gain insight into data and discover relationships between data.
After you have worked hard to classify all data, you can imagine some innovative ways to display data.
Back to top
Conclusion
Through this article, you understand the basic structure of the XML document and a simple method to parse XML data in PHP using SimpleXML. You have also added the ability to process HTML in a similar way, and initially learned how to traverse a website to retrieve data not provided in XML format. Using these tools and some examples provided in this article, you now have a good knowledge base and can start data mining for a website. There is still a lot of knowledge to learn about this topic, and they cannot be introduced one by one in an article. For more information about how to increase your data mining knowledge, see references.
Back to top
Download
Description download method of name size
| Source code |
Datamining_source.zip |
10KB |
HTTP |
Information about the download method