Reputation: 513
First of all, I've seen a good deal of similar questions. I know regex or dom can be used, but I can't find any good examples of DOM and regex makes me pull my hair. In addition, I need to pull out multiple values from the html source, some simply contents, some attributes.
Here is an example of the html I need to get info from:
<div class="log">
<div class="message">
<abbr class="dt" title="time string">
DATA_1
</abbr>
:
<cite class="user">
<a class="tel" href="tel:+xxxx">
<abbr class="fn" title="DATA_2">
Me
</abbr>
</a>
</cite>
:
<q>
DATA_3
</q>
</div>
</div>
The "message" block may occur once or hundreds of times. I am trying to end up with data like this:
array(4) {
[0] => array(3) {
["time"] => "DATA_1"
["name"] => "DATA_2"
["message"] => "DATA_3"
}
[1] => array(3) {
["time"] => "DATA_1"
["name"] => "DATA_2"
["message"] => "DATA_3"
}
[2] => array(3) {
["time"] => "DATA_1"
["name"] => "DATA_2"
["message"] => "DATA_3"
}
[3] => array(3) {
["time"] => "DATA_1"
["name"] => "DATA_2"
["message"] => "DATA_3"
}
}
I tried using simplexml but it only seems to work on very simple html pages. Could someone link me to some examples? I get really confused since I need to get DATA_2 from a title attribute. What do you think is the best way to extract his data? It seems very similar to XML extraction which I have done, but I need to use some other method.
Upvotes: 0
Views: 163
Reputation: 16462
Here is an example using DOMDocument and DOMXpath to parse your HTML.
$doc = new DOMDocument;
$doc->loadHTMLFile('your_file.html');
$xpath = new DOMXpath($doc);
$res = array();
foreach ($xpath->query('//div[@class="message"]') as $elem) {
$res[] = array(
'time' => $xpath->query('abbr[@class="dt"]', $elem)->item(0)->nodeValue,
'name' => $xpath->query('cite/a/abbr[@class="fn"]', $elem)->item(0)->getAttribute('title'),
'message' => $xpath->query('q', $elem)->item(0)->nodeValue,
);
}
Upvotes: 2
Reputation: 256
Can I suggest using xPath? It seems like a perfect candidate for what you want to do (but I may be misinterpreting what you're asking).
XPath will let you select particular nodes of an XML/HTML tree, and then you can operate on them from there. After that, it should be a simple task (or a tiny bit of simple regex at most. Personally, I love regex, so let me know if you need help with that).
Your XPath statements will look something like (assuming no conflicting names):
time (data 1):
/div/div/abbr/text()
name (data 2):
/div/div/cite/a/abbr/@title
message (data 3):
/div/div/q/text()
You can get more tech than this if, for example, if you want to identify the elements via their attributes, but what I've given you will be pretty fast.
Upvotes: 0