Jump to content

foreach looping and parsing XML


jake74

Recommended Posts

I'm using XPATH and PHP to try to parse several megabytes of tweets in one HTML document.  I want to get a CSV of three elements of the tweets, the user, the tweet content, and the date.  My Source looks like this (thousands of <li>'s:

<li class="result ">
  <div class="avatar">
<a href="http://twitter.com/shadowbottle" target="_blank"><img src="http://a1.twimg.com/profile_images/74217864/MeBlue_normal.jpg" /></a>
</div>
  <div class="msg">
        <a href="http://twitter.com/shadowbottle" target="_blank">shadowbottle</a>: <span id="msgtxt5128982567" class="msgtxt en"><b>NASA</b> should have charged for it's <b>iPhone</b> app or allowed variable pricing so it could double as donations.</span>

  </div>
    <div class="info">
  	Oct 24, 2009 07:06 PM GMT ·
              <span class="source">from <a href="http://twitterrific.com" rel="nofollow">Twitterrific</a></span>
        ·
    <a href="http://twitter.com/?status=@shadowbottle%20&in_reply_to_status_id=5128982567&in_reply_to=shadowbottle" class="litnv" onclick="pageTracker._trackPageview('/exit/reply/shadowbottle');" target="_blank">Reply</a>
    · <a href="http://twitter.com/shadowbottle/statuses/5128982567" class="lit" onclick="pageTracker._trackPageview('/exit/status/5128982567');" target="_blank">View Tweet</a>
</div>
    <p class="clearleft"></p>
  </li>

 

My PHP code can pull out the elements I want and list them all, but how do I setup my foreach loops so the code gets, element1, element2, and element3, then give me a line break?

 

Here's my slop

$file = $DOCUMENT_ROOT. "BigOlPageOfTweets.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

$xpath = new DOMXpath($doc);


$users = $xpath->query("/html/body/div[@id='main']/div[@id='mainContent']/div[@id='results']/ul/li[*]/*");
$tweets = $xpath->query("/html/body/div[@id='main']/div[@id='mainContent']/div[@id='results']/ul/li[*]/div[@class='msg']/span[*]");

  foreach ($users as $user) {
    $usernodes = $user->childNodes;
          echo "<br />";
    foreach ($usernodes as $node) {
    echo $node->nodeValue;
    }
  }

Thanks in advance.  This just comes down to my lack of being properly trained in coding logic, I've learned through Googling and hacking others code.

Link to comment
https://forums.phpfreaks.com/topic/180566-foreach-looping-and-parsing-xml/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.