PHP - Getting Started With Domdocument
Hi guys, Just starting to play with PHP Domdocument, only to fail at the very first step: <?php $html = 'test/php/somefile.html' ; if(!empty($html)){ $dom_1 = new domDocument ; $dom_1->loadHTML($html) ; $links = $dom_1->getElementsByTagName('li') ; foreach ( $links as $link) { // echo $link ; echo $link->nodeValue, PHP_EOL; } } ?> When I visit it in a browser I get a WSOD, what am I missing? Similar TutorialsDelete ... need to change host .. I'm trying to learn how to create a simple API, possibly using REST. I found a lot of online tutorials on how to implement API's but how do I create my own for my own website? The API I want to make is just for querying simple data and inserting data in the DB. From what I learned, REST does HTTP requests from a XML or JSON file but is REST a script I have to download, I can't find a REST site. I'm confused.. Hi guys, I am new to php and mySQL. I am trying to just learn how to input and output data to a mySQL database. What I want to do is have a single page with a text area and button where a user can enter some text and then press a submit button. When the button is pressed I want the text that the user typed to be entered in my database and then displayed below the text area. If you have any questions about what I am trying to do please ask. Thank you for your help in advance! Hello, I've just begun learning PHP and I've gotten a bit into it, but I'm nowhere near a pro. Now, I've decided to start a project that will, in my opinion, help me learn a lot. I'm just having a bit of trouble understanding exactly how to do a few things. My goal is to take the PHP forum base found here and turn it into something similar to this. I've made changes of my own to this forum base and have already finished the news posting section of it on the front page. (almost, one issue with that, more on that in a sec). I've also removed this portion: if(!$action || !in_array($action,$actions_array)){ $sql1 = "SELECT * FROM `forum_cats` WHERE `admin` < ".$row['admin']."+1"; $res1 = mysql_query($sql1) or die(mysql_error()); $i=1; while($row2 = mysql_fetch_assoc($res1)){ echo "<div id=\"fcontent\">\n"; echo " <div class=\"header\" id=\"header_".$i."\" onMouseOver=\"this.className='headerb'\" onMouseOut=\"this.className='header'\">".$row2['name']."</div>\n"; $sql2 = "SELECT * FROM `forum_sub_cats` WHERE `cid`='".$row2['id']."' AND `admin` < ".$row['admin']."+1"; $res2 = mysql_query($sql2) or die(mysql_error()); while($row3 = mysql_fetch_assoc($res2)){ echo " <div id=\"content\">\n"; echo " <a href=\"./index.php?act=forum&id=".$row3['id']."\">".$row3['name']."</a><br>\n"; echo " " . $row3['desc'] . "\n"; echo " </div>\n"; } echo "</div>\n"; $i++; } }else { from index.php so that instead of the links displayed as they would be on a forum, they can be displayed in a navbar off to the side as on the example site (this). That point leads me to my next point: the navigation bar. I'm looking to create the same sort of look (in terms of layout, not the whole.. dark design harry potter thing) as the example site, but I don't really understand how to make navbars on the sides of the whole.. news section. I just need a basic explanation of how these things can be done, but please do not give things away. After all, it is a learning experience. All help is appreciated, though! Also, let me know if you need any more information or if I was unclear. Thanks, Fae I'm going to go for broke here as this is the last thing I can think of that is going to help me learn anything... First things first. I have been reading tutorials and guides and all other things about PHP and playing around with all the codes from these tutorials and guides on my localhost. All work well. Yet, they haven't really taught me a great deal since all the code is already written and it's extremely hard to customize with the limited knowledge I currently have. I do not learn very well from sitting down and reading something that someone else has already written and then trying to work out what all the parts are. When I look at some code - I can usually figure out what is happening and what the code is doing. But it doesn't really help me understand how to write the code myself... So I thought if I made a topic where I get people to help ME write out a complete code.. I would actually learn something as I go along.. asking questions where I need to and building it exactly the way I want it. Note the 'ME' is capitalized. I don't expect everyone else to write it all down for me. I want to write it - have you guys give it the ok and we'll move on to the next bit. I know there will be parts where I am completely lost and I will need people to write down something to keep the whole thing moving. I would then ask questions untill I understood what you have provided. The whole idea of this is to build a User Login/Management system. If anyone is up for supporting this idea and helping me start from scratch let me know. Otherwise I'm not sure what else I'm going to have to do. Hey Guys, Im having a really frustrating problem with this set of PHP: writeConversationFunctions.php <?php session_start(); the function writeMessage($message){ $_SESSION['messagetest'] = $message; $chatLogFile = "log.txt"; $openChatLog = fopen($chatLogFile, 'w') or die("Failed to open Log File."); if($message == "resetnow"){ $message = ""; fwrite($openChatLog, $message); fclose($openChatLog); $_SESSION['lastMessageSize'] = 0; } elseif($message == ""){ } else{ $timestamp = date("h:i"); if(isset($_SESSION['username'])){ $username = $_SESSION['username']; } else{ $username = "Anonymous"; } if($message[0] == "/"){ $commandString = stripslashes($commandString); $commandString = htmlentities($commandString, ENT_QUOTES, 'UTF-8'); $commandString = substr($commandString, 1); $command = explode(" ",$commandString); switch ($command[0]){ case "slap": $name = command[1]; $commandResponse = '<p class="commandText">' ."You slap " . $name . "across the face.</p>"; fwrite($openChatLog, $commandResponse); fclose($openChatLog); break; } } else{ $message = stripslashes($message); $message = htmlentities($message, ENT_QUOTES, 'UTF-8'); $message = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $message); $messageString = ' <p class="message"> <span class="timestamp">' .$timestamp . '</span> <span class="username">' . $username . ': </span>' . $message . '</p>'; fwrite($openChatLog, $messageString); fclose($openChatLog); } } } writeMessage($_POST['message']); ?> Simply, the session at the top will not be created for some reason. The post data is sent from: index.php Code: [Select] <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="styles.css" /> <title>Chatulo.us</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> <script> var n = 0; $(document).ready(function () { var focused = true; $(window).focus(function () { focused = true; f(); }); $(window).blur(function () { focused = false; f(); }); var title = document.title; var f = function () { if (focused) { n = 0; document.title = "Chatulo.us / Home"; } else { // none of that else if needed here, you're only checking is focused or not. if (n == 0) { // now you're checking if its zero, so ... document.title = "Chatulo.us / Home"; } else { // you need ELSE here, otherweise you'll always use this next clause document.title = "(" + n + ") " + "Chatulo.us / Home"; } } }; function playSound(soundfile) { document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />"; } $.ajax({ type: "POST", url: "loginHandlers.php", data: { required_function: "checkSession" }, success: function (response) { $('#usernameBox').html(response); } }); $("form#sendMessageForm").submit(function () { var message = $('#messageInputField').attr('value'); $('#messageInputField').val(''); $.ajax({ type: "POST", url: "writeConversationFunctions.php", data: { message: message }, success: function () { update(); } }); return false; }); function update() { $.ajax({ type: "POST", dataType: "json", url: "readConversationFunctions.php", data: { required_function: "readConvo" }, success: function (message) { if (message.newmessage == true) { $('#messageBox').html(message.message); playSound('sounds/pop.mp3'); n = n + 1; f(); } else if (message.newmessage === false) { $('#messageBox').html(message.message); } }, complete: function () { setTimeout(update, 1000) $("#messageBox").attr({ scrollTop: $("#messageBox").attr("scrollHeight") }); } }); } $("form#getUsernameForm").live('submit', function () { var username = $('#usernameInputField').attr('value'); $.ajax({ type: "POST", url: "loginHandlers.php", data: { username: username, required_function: "usernameHandler" }, success: function (response) { $('#usernameBox').html("Processing..."); setTimeout(function () { $('#usernameBox').html(response) }, 1000); } }); return false; }); $("span#logoutText").live('click', function () { $.ajax({ type: "POST", url: "loginHandlers.php", data: { required_function: "removeSession" }, success: function (response) { $('#usernameBox').html("Processing..."); setTimeout(function () { $('#usernameBox').html(response) }, 1000); } }); return false; }); update(); }); </script> </head> <body> <form method="post" name="messageInput" id="sendMessageForm"> <input name="message" id="messageInputField" type="text" autocomplete="off"/> <input name="submit" type="submit" value="Send"/> </form> <div id="messageBox"> </div> <div id="usernameBox"> </div> <span id="dummy"></span> <img src="images/logo.png" width="175" height="50" alt="Logo" id="chatulouslogo"/> </body> </html> Any help with this issue would be GREATLY appreciated! Regards, Cody hey guys i'am newb in php and i'am doing some algorithm in php, in some codes i need to use session but in that particular page the code does not know if session_start() has been called or not. wonder to if there is anyway that i can get if session is started or not in my code? thanks in advance This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=332465.0 Is there any reason that people can think as to why DOMDocument::saveHTML would remove the following: Code: [Select] <![if !vml]> <img src="someimage.jpg" /> <![endif]> A little clarification... This HTML comment tag is used in my company's email newsletter code and is necessary to make Outlook 2007 behave properly. For whatever reason, saveHTML strips it out. I know that this doesn't conform to HTML standards and I'm guessing that that is why it is being stripped. BUT, from reading on the internet, saveHTML can produce junk html code anyways. Any help is appreciated. Hi all, I am pretty new to php and I am having an issue trying to load an XML document. When ever I try to use Xpath it negates all the code below the line, including the HTML, and returns a white page. here is my code: Code: [Select] <html> <head> <?php $xpath = new DOMXPath("structure.xml"); ?> <body> hello world </body> </html> I checked phpinfo() and I have both the DOM and XPath enables and installed. I have also tried using just DOM and that worked so it is only Xpath that is not working. Ideas? Thank you James S I have some code $doc = new DOMDocument(); $doc->loadHTML( '<html> <head><title>Test</title></head> <body></body></html>' ); $doc->encoding = 'iso-8859-1'; file_put_contents('test.html', $doc->saveHTML()); when i view the output file i get <html><head><title>Test</title></head><body></body></html> all on one line is there no way of having it format it like the original source code so that its not all bunched together? I am finally getting my blog started. Actually having allot of fun with it to be honest, so far what I have been thinking about is actually working for a change lol. This is more in some ways to show you what I can do actually aswell, all of the below code is obviously in procedural, but would you change anything at all? I mean I know all of the below code is going to be a matter of preference, it works though so far, but I have been reading a few books and sort of memorised allot of it, all of the code below is my own perceptions of course, what do you think? Here's my logic (I have excluded my 'inc.database.php' file, as that's got my mysql database login details), here it is anyways: Code: [Select] <?php ini_set('display_errors', 1); // include the database connection! require_once 'inc.database.php'; function get_category($category_id) { $sql = 'SELECT category FROM blog_categories WHERE category_id = '.$category_id; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); extract($row); return $category; } // function get_responses($category_id, $post_id){ function get_responses($post_id){ $post_id = mysql_real_escape_string($post_id); $sql = 'SELECT post_title, post_text, date FROM blog_posts WHERE isreply = 1 AND parent = '.$post_id; $result = mysql_query($sql); return mysql_num_rows($result); } require_once 'header.html'; // if user has not selected a category in the URL then display the category links! if(!isset($_GET['category'])) { printf("<p>Please select a blog category</p>\n"); $sql = 'SELECT category_id, category FROM blog_categories WHERE avail = \'Y\' ORDER BY category'; $result = mysql_query($sql); // weird but if there's an error show the user firstly! if(!$result) { printf("<p class=\"error\">Could not contact server, please try again later.</p>"); } else { if(mysql_num_rows($result) > 0) { // else loop and output the category as links, so get can be retrieved the find all the posts: while($row = mysql_fetch_assoc($result)) { extract($row); // turns headings of column names into variables, so dont have to use $row['colname'] in database, like so: printf("<p><a href=\"index.php?category=%d\">%s</a><br /></p>\n", $category_id, $category); } } else { printf("<p>No categories available</p>"); } } } else { // trim the category, so someone isnt being stupid and tries to create like a DOS with empty spaces in the category URL trim($_GET['category']); // removes any blank spaces // if category ident is not empty: if($_GET['category'] != ''){ // make input safe: $category_id = mysql_real_escape_string($_GET['category']); // now need to select from which category it is! $sql = "SELECT post_id, post_title, post_text, date, username, category FROM blog_posts LEFT JOIN blog_users ON blog_posts.user_id = blog_users.user_id INNER JOIN blog_categories ON blog_posts.category_id = blog_categories.category_id WHERE blog_posts.category_id = $category_id AND approved = 1 AND isreply != 1"; $result = mysql_query($sql); printf("\n<h2>%s</h2>\n", get_category($category_id)); // calls a function to get the category name! if(mysql_num_rows($result) > 0) { // display the rows of posts: while($row = mysql_fetch_assoc($result)) { extract($row); printf("<h3>%s</h3>\n %s<br />\n By %s %s \n<br />", $post_title, $post_text, $username, $date); // get the no of replies and maybe even at some point show the oldest replies first: // get_responses($category_id, $post_id); printf("No of comments %d</p>",get_responses($post_id)); } } else { printf("<p>No posts exist in this category</p>\n"); } } else { printf("<p class=\"error\">You did not select a blog category, please try again.</p>"); } } require_once 'footer.html'; ?> Of course with the init_set('display_errors', 1) is set to true just for debugging though, when I am happy with it going live I will make this 0, so no errors appear to the user, but what do you think? It is of course entirely reading from the database, no input on this page, as that will be on other scripts. Thanks and I look forward to any replies, Jez. Hi guys, Reading this from php.net, has got me a wee bit confused. Trying to implement is has got me doubly confused! My code: $dom = new DOMDocument; libxml_use_internal_errors(true); $dom->loadHTMLFile($parent_node); if($dom->childNodes <>0) { $kids = array ( 'url' => $parent_node, 'No_of_kids' => count($dom->childNodes) ); } Results in '' Notice: Object of class DOMNodeList could not be converted to int' How the heck am i supposed to count the childNodes? Code: [Select] $domdoc=new DOMDocument(); $domdoc->formatOutput=TRUE; $empty_cart_xml= '<Order> <Cart> <Items> <Item>1</Item> <Item>2</Item> <Item>3</Item> </Items> </Cart> </Order>'; $domdoc->loadXML($empty_cart_xml); print $domdoc->saveXML()."<hr/>"; //works up to this point $xpath=new DOMXPath($domdoc); $items=$xpath->query('Order/Cart/Items'); foreach($itemses AS $items) { $items->appendChild($domdoc->createElement('Item','4')); } print $domdoc->saveXML(); All I want to do is to add a new Item to Items. What am I doing wrong? I just finished (or so I thought) a project. But my client's server runs PHP4, so I need to adapt my code. Here's what stopped working: Code: [Select] $localClasses = new DOMDocument; $localClasses -> load("file.xml"); $localClasses -> get_elements_by_tagname('Title') -> item(0) -> firstChild -> nodeValue Here's my petty attempt at trying to adapt this code to run in PHP4: Code: [Select] $file = file_get_contents("localClasses.xml"); $localClasses = new DOMDocument($file); $test = $localClasses -> get_elements_by_tagname('Title'); $testText = $test -> item[0] -> firstChild -> nodeValue; print $testText; This doesn't give me any errors, but nothing shows up. Any help would be appreciated. Thanks for reading! Imagine an html with the following structure Code: [Select] <div class="item"> <div class="title"> <a class="title" href="http://www.domain.com/title.html">Title is here</a> </div> <div class="image"> <a href="http://www.domain.com/title.html"><img src=image.jpg /></a> </div> </div> How to make an array containing $title - $url - $image_url ? good evening dear PHPFreaks - hello to everybody. i want to create a link parser. i have choosen to do it with Curl. I have some lines together now. Love to hear your review... Since i am new to programming i love to get some hints from experienced devs. Here some details: well since we have several hundred of resultpages derived from this one: http://www.educa.ch/dyn/79362.asp?action=search Note: i want to itterate over the resultpages - with a loop. http://www.educa.ch/dyn/79376.asp?id=1568 http://www.educa.ch/dyn/79376.asp?id=2149 i take this loop: for($i=1;$i<=$match[1];$i++) { $url = "http://www.example.com/page?page={$i}"; // access new sub-page, extract necessary data } Dear PHP-Freaks, what do you think? What about the Loop over the target-Urls? BTW: you see - there will be some pages empty. Note - the empty pages should be thrown away. I do not want to store "empty" stuff. well this is what i want to. And now i need to have a good parser-script. Note: this is a tree-part-job: 1. fetching the sub-pages 2. parsing them 3. storing the data in a mysql-db Well - the problem - some of the above mentioned pages are empty. so i need to find a solution to leave them aside - unless i do not want to populate my mysql-db with too much infos.. Btw- parsing should be a part that can be done with DomDocument - What do you think? I need to combine the first part with tthe second - can you give me some starting points and hints to get this. The fetching-job should be done with CuRL - and to process the data into a DomDocument-Parser-Job. note ive taken the script from this place: http://www.merchantos.com/makebeta/php/scraping-links-with-php/ function storeLink($url,$gathered_from) { $query = "INSERT INTO links (url, gathered_from) VALUES ('$url', '$gathered_from')"; mysql_query($query) or die('Error, insert query failed'); } for($i=1;$i<= 10000; $i++) { $target_url = "http://www.educa.ch/dyn/79376.asp?id={$i}"; } // access new sub-page, extract necessary data $userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)'; // make the cURL request to $target_url $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); curl_setopt($ch, CURLOPT_URL,$target_url); curl_setopt($ch, CURLOPT_FAILONERROR, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $html= curl_exec($ch); if (!$html) { echo "<br />cURL error number:" .curl_errno($ch); echo "<br />cURL error:" . curl_error($ch); exit; } // parse the html into a DOMDocument $dom = new DOMDocument(); @$dom->loadHTML($html); // grab all the on the page $xpath = new DOMXPath($dom); $hrefs = $xpath->evaluate("/html/body//a"); for ($i = 0; $i < $hrefs->length; $i++) { $href = $hrefs->item($i); $url = $href->getAttribute('href'); storeLink($url,$target_url); echo "<br />Link stored: $url"; } Dear PHP-Freaks, what do you think? What about the Loop over the target-Urls? love to hear from you ! so there's some html i'm having to fetch and parse for personal use...but some of the data i want is started in a table written this way: rawTableData = {"rows": [{"colname1": value, "colname2": "value", "colname3: value} how can i use domdocument to parse this data if say i want the value for colname2? there are no tags for me to use. It is easy to get image or link by DomDocument, but I did not find a way to get image with its target link. Imagine a html as Code: [Select] <div class=image> <a href='http://site.com'><img src='imagelink.jpg'></a> </div>How to get both the image link and href? $dom = new DOMDocument(); @$dom->loadHTML($html); $xpath = new DOMXPath($dom); $hrefs = $xpath->evaluate("/html/body//div[@class='image']"); for ($i = 0; $i < $hrefs->length; $i++) { $href = $hrefs->item($i); Now to get the image and its href, we need first getElementsByTagName('a') and getElementsByTagName('img') but they do not work inside foreach. What's your idea? Hi, I have a php code that could extract the categories and display them. However, I still can't extract the numbers that goes along with it too(without the bracket).
This is my code:
<?php $grep = new DoMDocument(); @$grep->loadHTMLFile("http://www.lelong.com.my/Auc/List/BrowseAll.asp"); $finder = new DomXPath($grep); $class = "CatLevel1"; $nodes = $finder->query("//*[contains(@class, '$class')]"); foreach ($nodes as $node) { $span = $node->childNodes; echo $span->item(0)->nodeValue."<br>"; } ?>This is my desired output: Arts, Antiques & Collectibles : 9768 B2B & Industrial Products : 2342 Baby : 3453 etc...Any help is appreciated. Thanks! |