PHP - Parserscript With Curl & Xpath Needs Some Final Reviews - All Ready Have A Look!
Similar TutorialsSo here's what I'm trying to do, and I haven't found any clear tutorials on how to properly navigate a DOMDocument object, at least not in the strict sense of PHP. I'm building a web scraper, I've had it working for some time now using more traditional methods (a combination of string manipulation and clever regex). I've been told xpath can be much faster and more reliable for what I need. Sold. Let's say I'm parsing a forum. This forum separates each reply in a post with a set of <li></li> with a class of "message" Code: [Select] <li class="message"> // Stuff here </li> <li class="message"> // Stuff here </li> So far so good. These list items contain all the formatting for each post, including user info and the message text. Each sitting in it's own div. Code: [Select] <li class="message"> <div class="user info"> User info here </div> <div class="message text"> Message text here </div> </li> <li class="message"> <div class="user info"> User info here </div> <div class="message text"> Message text here </div> </li> Still with me? Good. With this bit of code I can select each message list item block and iterate over all the sub nodes inside. Code: [Select] $items = $xpath->query("//li[starts-with(@class, 'message')]"); for ($i = 0; $i < $items->length; $i++) { echo $items->item($i)->nodeValue . "\n"; } This produces a basic text dump of the entire forum. Close, but not what I need. What I'm trying to do is as follows Select all the class="message" list items [done] Once those have been selected, run another $xpath->query to select the child nodes which contain the user info and message text Step one is done, step two is what is confusing me. How can I run a new query based on the output from the first query? Thanks guys Hello dear Community, hello dear Andy I want to parse a site that is called the foundation-finder: My Perl knowledge is pretty small! I have tried various tutorials (examples of Mecha - that i have found on the CPAN) not oll of them work - some of them are broken! Now i try t o get some real-world-task! the Foundation-Finder-task has several steps: Especially interesting for me as a PHP/Perl-beginner is this site in Switzerland: http://www.edi.admin.ch/esv/00475/00698/index.html?lang=de&webgrab_path=http://esv2000.edi.admin.ch/d/entry.asp?Id=3221 which has a dataset of 2700 foundations. All the data are free to use - with no limitations copyrights on it. i mused about a starting-point: ould i use a Perl-module from CPAN and do the job with Perl.I guess that Mechanize or LWP could do a great job. Or HTML::Parser well - i am just musing which is the best way to do the job. Guess that i am in front of a nice learning curve. This task will give me some nice PHP or Perl lessions. Or can we do this with Python either!? I guess so! So here i am! So here is a sample-page for the real-world-task a governmental site in Switzerland: more than 2'700 foundations in http://www.edi.admin.ch/esv/00475/00698/index.html?lang=de&webgrab_path=http://esv2000.edi.admin.ch/d/entry.asp?Id=3221 can i do this with mecha!? love to get a hint thanks matz Hello Friends i just need your reviews for the following code Code: [Select] <?php session_start(); require_once("conf.php"); mysql_select_db('site'); $subjects=$_GET['sublen']; $username=$_SESSION['user']; for($i=1;$i<=$subjects;$i++) { $subject=$_GET[',Sub'.$i]; $query="INSERT INTO Subjects(id,Subjects,User,Classs) VALUES($i,'$subject','$username','F.Y.B.Sc')"; $true=mysql_query($query) or die("Cannot Store subjects".mysql_error()); } ?> Is this a valid way to store data in database???? <?php $con = mysql_connect("localhost","root","password"); if (!$con) { die('Could not connect:' . mysql_error()); } mysql_select_db("Products", $con); $result = mysql_query("SELECT * FROM btp_reviews" ); echo "<table border='1' cellspacing='0' cellpadding='0'>"; echo '<tr> <td>Id</td> <td>Review</td> <td>Name</td> <td>Update</td> <td>Status</td> </tr>'; while($row = mysql_fetch_assoc($result)) { echo '<tr>'; echo '<td>' . $row['id'] . '</td>'; echo "<td>" . $row['review'] . "</td>"; echo "<td>" . $row['r_name'] . "</td>"; echo "<td>" ."<form action='radio.php' method='post' ><a href=http://localhost/editt.php?id=".$row['id'].">Edit</a>.</td> <td>" ."<input type='radio' name='r1' value='2' />Approve<br/><input type=hidden name=id value='".$row['id']."' /> <input type='radio' name='r1' value='3' /> Reject<br/> <input type=submit value=Submit /></form>"."</td>"; } echo "</table>"; mysql_close($con); ?>
I would like to pull in Facebook reviews from my Facebook page and display them on a page on my website but am new to doing that so just seeing if there is any sample code I can get from somewhere to have a look at please? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=317436.0 hello dear php-freaks
well this is just a question that came up to my mind today:
can we put amazon-customer reviews on private websites just ran across this statement: aybe. I wrote the original answer below earlier. I don't have time to look into this right now because I'm no longer on a project concerned with Amazon reviews, but their webpage at Product Advertising API states "The Product Advertising API helps you advertise Amazon products using product search and look up capability, product information and features such as Customer Reviews..." as of 2011-12-08. So I hope someone looks into it and posts back here; feel free to edit this answer. derived he https://stackoverflo...9451851#9451851 so what is the case: just let us know ? Well there are some plugins out there that do that: eg. for wordpress we can use ScrapeAZon. I guess that it does exactly what many many are loooking for. cf https://wordpress.or...on/screenshots/ On a shortnote: probably it is not allowed in some states - in others it probalby will be allowed. What do you say.. I hear CakePHP 3.0 being talked about like its something for the future but I also see that you can download it and there are tutorials for it out already. Is it ready for developmental use, or is it still too early for that?
I, for some unknown reason, decided to attempt to build my first social networking website for my senior project. I am sort of a dumb dumb when it comes to PHP. For what I am currently working on now I need to display "members" that go to the same "school" and start in the same "semester" according to whomever is currently logged in. I understand $_SESSION['userid'] = mysql_insert_id(); is tracking the current user, but how would I track other information attached to that current user. The "school" and "semester" are tracked within tables outside of the "user" table. Any help at all would be awesome. If you need anymore information let me know. Thanks a trizillion. My parser: <?php if (isset($_GET['formSubmit'])) { $option = $_GET['option']; $option = array_values($option); if (!empty($option)){ $xml = simplexml_load_file('differences.xml'); $i = 0; $count = count($option); ?> <table> <tr> <td>Item</td> <td>Code</td> <td>Type</td> <td>Level</td> </tr> <?php while($i < $count) { $selected = $xml->xpath("//item[contains(@name,'".$option[$i]."')]"); echo "<tr>"; echo "<td>".$selected[0]['name']."</td>"; echo "<td>".$selected[0]['code']."</td>"; echo "<td>".$selected[0]['type']."</td>"; echo "<td>".$selected[0]['requiredLevel']."</td>"; echo "</tr>"; $i++; } ?> </table> This works great however requiredLevel is showing nothing. Here is what is stored in the $selected array: Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [buildingName] => EiffelTower [code] => lM [type] => building ) [requiredLevel] => 5 [cost] => 5000 [built] => 03/31/1889 => SimpleXMLElement Object ( [@attributes] => Array ( [itemClass] => EiffelTower_construct ) ) [defaultItem] => SimpleXMLElement Object ( [@attributes] => Array ( [amount] => 1 [name] => iron ) ) [finishedReward] => iron [image] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [loadClass] => mc [name] => construct_0 [url] => /buildings/eiffel_tower.swf ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [loadClass] => mc [name] => construct_1 [url] => /buildings/eiffel_tower.swf ) ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [loadClass] => mc [name] => built_0 [url] => /buildings/eiffel_tower.swf ) ) [3] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => icon [url] => buildings/eiffel_tower.png ) ) [4] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => startIcon [url] => /buildings/eiffel_tower.png ) ) [5] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => halfIcon [url] => /buildings/eiffel_tower.png ) ) [6] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => completeIcon [url] => /buildings/eiffel_tower.png ) ) ) [constructionUI] => /buildings/Construct_eiffel_tower.swf [countryCard] => france ) My XML: <element> <item code="lM" name="snowman2010" type="building"> <requiredLevel>5</requiredLevel> <cost>5000</cost> <built>03/31/1889</built> <storageType itemClass="EiffelTower_construct"/> <defaultItem amount="1" name="iron"/> <finishedReward>iron</finishedReward> <image loadClass="mc" name="construct_0" url="/buildings/eiffel_tower.swf"/> <image loadClass="mc" name="construct_1" url="/buildings/eiffel_tower.swf"/> <image loadClass="mc" name="built_0" url="/buildings/eiffel_tower.swf"/> <image name="icon" url="/buildings/eiffel_tower.png"/> <image name="startIcon" url="/buildings/eiffel_tower.png"/> <image name="halfIcon" url="/buildings/eiffel_tower.png"/> <image name="completeIcon" url="/buildings/eiffel_tower.png"/> <constructionUI>/buildings/eiffel_tower.swf</constructionUI> <countryCard>france</countryCard> </item> Using the established code pattern in my parser.php how can I print out requiredLevel? The output of my array is mighty confusing! [/code] good day dear community, i am workin on a Curl loop to fetch multiple pages: i have some examples - and a question: Example: If we want to get information from 3 sites with CURL we can do it like so: $list[1] = "http://www.example1.com"; $list[2] = "ftp://example.com"; $list[3] = "http://www.example2.com"; After creating the list of links we should initialize the cURL multi handle and adding the cURL handles. $curlHandle = curl_multi_init(); for ($i = 1;$i <= 3; $i++) $curl[$i] = addHandle($curlHandle,$list[$i]); Now we should execute the cURL multi handle retrive the content from the sub handles that we added to the cURL multi handle. ExecHandle($curlHandle); for ($i = 1;$i <= 3; $i++) { $text[$i] = curl_multi_getcontent ($curl[$i]); echo $text[$i]; } In the end we should release the handles from the cURL multi handle by calling curl_multi_remove_handle and close the cURL multi handle! If we want to another Fetch of sites with cURL-Multi - since this is the most pretty way to do it! Well I am not sure bout the string concatenation. How to do it - Note I want to fetch several hundred pages: see the some details for this target-server sites - /(I have to create a loop over several hundred sites). * siteone.example/?show_subsite=9009 * siteone.example/?show_subsite=9742 * siteone.example/?show_subsite=9871 .... and so on and so forth Question: How to appy this loop into the array of the curl-multi? <?php /************************************\ * Multi interface in PHP with curl * * Requires PHP 5.0, Apache 2.0 and * * Curl * ************************************* * Writen By Cyborg 19671897 * * Bugfixed by Jeremy Ellman * \***********************************/ $urls = array( "siteone", "sitetwo", "sitethree" ); $mh = curl_multi_init(); foreach ($urls as $i => $url) { $conn[$i]=curl_init($url); curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1);//return data as string curl_setopt($conn[$i],CURLOPT_FOLLOWLOCATION,1);//follow redirects curl_setopt($conn[$i],CURLOPT_MAXREDIRS,2);//maximum redirects curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,10);//timeout curl_multi_add_handle ($mh,$conn[$i]); } do { $n=curl_multi_exec($mh,$active); } while ($active); foreach ($urls as $i => $url) { $res[$i]=curl_multi_getcontent($conn[$i]); curl_multi_remove_handle($mh,$conn[$i]); curl_close($conn[$i]); } curl_multi_close($mh); print_r($res); ?> I look forward to your ideas. I apologize for starting a couple of threads. But I have finally typed out my entire dilemma and could really use support in solving this issue. I am having an extremely hard time with I am sure a simple solution. I am slightly new at programming, but I know a fair amount to get my by. Anyways... Here's my problem. I am a photographer and I working on a website to teach and train students. I have currently made a very detailed website, but photo uploading management is kicking my butt. I first begin with an iFrame. The code follows, <?PHP include('../functions.php'); if($loggedinid="") { header( 'Location: http://lightgraspers.com/login.php' ) ; } //session_start(); //$_SESSION['pid']=$_SERVER['QUERY_STRING']; //$loggedinid=$_SESSION['uid']; //$_SESSION['pid']=$pid; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Queued Photo Uploader - Standalone Showcase from digitarald.de</title> <meta name="author" content="Harald Kirschner, digitarald.de" /> <meta name="copyright" content="Copyright 2009 Harald Kirschner" /> <!-- Framework CSS --> <link rel="stylesheet" href="http://github.com/joshuaclayton/blueprint-css/raw/master/blueprint/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="http://github.com/joshuaclayton/blueprint-css/raw/master/blueprint/print.css" type="text/css" media="print"> <!--[if IE]><link rel="stylesheet" href="http://github.com/joshuaclayton/blueprint-css/raw/master/blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> <!--[if lte IE 7]> <script type="text/javascript" src="http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js"></script> <![endif]--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.2/mootools.js"></script> <script type="text/javascript" src="source/Swiff.Uploader.js"></script> <script type="text/javascript" src="source/Fx.ProgressBar.js"></script> <script type="text/javascript" src="http://github.com/mootools/mootools-more/raw/master/Source/Core/Lang.js"></script> <script type="text/javascript" src="source/FancyUpload2.js"></script> <!-- See script.js --> <script type="text/javascript"> //<![CDATA[ /** * FancyUpload Showcase * * @license MIT License * @author Harald Kirschner <mail [at] digitarald [dot] de> * @copyright Authors */ window.addEvent('domready', function() { // wait for the content // our uploader instance var up = new FancyUpload2($('demo-status'), $('demo-list'), { // options object // we console.log infos, remove that in production!! verbose: true, // url is read from the form, so you just have to change one place url: $('form-demo').action, // path to the SWF file path: 'source/Swiff.Uploader.swf', // remove that line to select all files, or edit it, add more items typeFilter: { 'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png' }, // this is our browse button, *target* is overlayed with the Flash movie target: 'demo-browse', // graceful degradation, onLoad is only called if all went well with Flash onLoad: function() { $('demo-status').removeClass('hide'); // we show the actual UI $('demo-fallback').destroy(); // ... and hide the plain form // We relay the interactions with the overlayed flash to the link this.target.addEvents({ click: function() { return false; }, mouseenter: function() { this.addClass('hover'); }, mouseleave: function() { this.removeClass('hover'); this.blur(); }, mousedown: function() { this.focus(); } }); // Interactions for the 2 other buttons $('demo-clear').addEvent('click', function() { up.remove(); // remove all files return false; }); $('demo-upload').addEvent('click', function() { up.start(); // start upload return false; }); }, // Edit the following lines, it is your custom event handling /** * Is called when files were not added, "files" is an array of invalid File classes. * * This example creates a list of error elements directly in the file list, which * hide on click. */ onSelectFail: function(files) { files.each(function(file) { new Element('li', { 'class': 'validation-error', html: file.validationErrorMessage || file.validationError, title: MooTools.lang.get('FancyUpload', 'removeTitle'), events: { click: function() { this.destroy(); } } }).inject(this.list, 'top'); }, this); }, /** * This one was directly in FancyUpload2 before, the event makes it * easier for you, to add your own response handling (you probably want * to send something else than JSON or different items). */ onFileSuccess: function(file, response) { var json = new Hash(JSON.decode(response, true) || {}); if (json.get('status') == '1') { file.element.addClass('file-success'); file.info.set('html', '<strong>Image was uploaded:</strong> ' + json.get('width') + ' x ' + json.get('height') + 'px, <em>' + json.get('mime') + '</em>)'); } else { file.element.addClass('file-failed'); file.info.set('html', '<strong>An error occured:</strong> ' + (json.get('error') ? (json.get('error') + ' #' + json.get('code')) : response)); } }, /** * onFail is called when the Flash movie got bashed by some browser plugin * like Adblock or Flashblock. */ onFail: function(error) { switch (error) { case 'hidden': // works after enabling the movie and clicking refresh alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).'); break; case 'blocked': // This no *full* fail, it works after the user clicks the button alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).'); break; case 'empty': // Oh oh, wrong path alert('A required file was not found, please be patient and we fix this.'); break; case 'flash': // no flash 9+ :( alert('To enable the embedded uploader, install the latest Adobe Flash plugin.') } } }); }); //]]> </script> <!-- See style.css --> <style type="text/css"> /** * FancyUpload Showcase * * @license MIT License * @author Harald Kirschner <mail [at] digitarald [dot] de> * @copyright Authors */ /* CSS vs. Adblock tabs */ .swiff-uploader-box a { display: none !important; } /* .hover simulates the flash interactions */ a:hover, a.hover { color: red; } #demo-status { padding: 10px 15px; width: 420px; border: 1px solid #eee; } #demo-status .progress { background: url(assets/progress-bar/progress.gif) no-repeat; background-position: +50% 0; margin-right: 0.5em; vertical-align: middle; } #demo-status .progress-text { font-size: 0.9em; font-weight: bold; } #demo-list { list-style: none; width: 450px; margin: 0; } #demo-list li.validation-error { padding-left: 44px; display: block; clear: left; line-height: 40px; color: #8a1f11; cursor: pointer; border-bottom: 1px solid #fbc2c4; background: #fbe3e4 url(assets/failed.png) no-repeat 4px 4px; } #demo-list li.file { border-bottom: 1px solid #eee; background: url(assets/file.png) no-repeat 4px 4px; overflow: auto; } #demo-list li.file.file-uploading { background-image: url(assets/uploading.png); background-color: #D9DDE9; } #demo-list li.file.file-success { background-image: url(assets/success.png); } #demo-list li.file.file-failed { background-image: url(assets/failed.png); } #demo-list li.file .file-name { font-size: 1.2em; margin-left: 44px; display: block; clear: left; line-height: 40px; height: 40px; font-weight: bold; } #demo-list li.file .file-size { font-size: 0.9em; line-height: 18px; float: right; margin-top: 2px; margin-right: 6px; } #demo-list li.file .file-info { display: block; margin-left: 44px; font-size: 0.9em; line-height: 20px; clear } #demo-list li.file .file-remove { clear: right; float: right; line-height: 18px; margin-right: 6px; } </style> </head> <body> <div class="container"> <!-- See index.html --> <div> <form action="server/script.php" method="post" enctype="multipart/form-data" id="form-demo"> <fieldset id="demo-fallback"> <label for="demo-photoupload"> Upload a Photo: <input type="file" name="Filedata" /> </label> </fieldset> <div id="demo-status" class="hide"> <p><?php echo "$conid", "$loggedin", "$loggedinid", "$pid", $_GET['pid'] ?> <a href="#" id="demo-browse">Browse Files</a> | <a href="#" id="demo-clear">Clear List</a> | <a href="#" id="demo-upload">Start Upload</a> </p> <div> <strong class="overall-title"></strong><br /> <img src="assets/progress-bar/bar.gif" class="progress overall-progress" /> </div> <div> <strong class="current-title"></strong><br /> <img src="assets/progress-bar/bar.gif" class="progress current-progress" /> </div> <div class="current-text"></div> </div> <ul id="demo-list"></ul> </form> </div> </div> </body> </html> I can carry the value of $loggedid over to the iFrame, but then it doesn't go with the server/script.php path. No variables pass through... Here is the script.php information: <?php include('../../functions.php'); // Request log /** * You don't need to log, this is just for the showcase. Better remove * those lines for production since the log contains detailed file * information. */ $result = array(); $result['time'] = date('r'); $result['addr'] = substr_replace(gethostbyaddr($_SERVER['REMOTE_ADDR']), '******', 0, 6); $result['agent'] = $_SERVER['HTTP_USER_AGENT']; if (count($_GET)) { $result['get'] = $_GET; } if (count($_POST)) { $result['post'] = $_POST; } if (count($_FILES)) { $result['files'] = $_FILES; } // we kill an old file to keep the size small //if (file_exists('script.log') && filesize('script.log') > 102400) { // unlink('script.log'); //} //$log = @fopen('script.log', 'a'); //if ($log) { // fputs($log, print_r($result, true) . "\n---\n"); // fclose($log); //} // Validation $error = false; if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name'])) { $error = 'Invalid Upload'; } /** * You would add more validation, checking image type or user rights. * if (!$error && $_FILES['Filedata']['size'] > 2 * 1024 * 1024) { $error = 'Please upload only files smaller than 2Mb!'; } if (!$error && !($size = @getimagesize($_FILES['Filedata']['tmp_name']) ) ) { $error = 'Please upload only images, no other files are supported.'; } if (!$error && !in_array($size[2], array(1, 2, 3, 7, 8) ) ) { $error = 'Please upload only images of type JPEG, GIF or PNG.'; } if (!$error && ($size[0] < 25) || ($size[1] < 25)) { $error = 'Please upload an image bigger than 25px.'; } */ // Processing /** * Its a demo, you would move or process the file like: * * move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/$loggedinid/' . $_FILES['Filedata']['name']); * $return['src'] = '/uploads/$loggedinid' . $_FILES['Filedata']['name']; * * or * * $return['link'] = YourImageLibrary::createThumbnail($_FILES['Filedata']['tmp_name']); * */ if ($error) { $return = array( 'status' => '0', 'error' => $error ); } else { $return = array( 'status' => '1', 'name' => $_FILES['Filedata']['name'] ); // Our processing, we get a hash value from the file $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']); // ... and if available, we get image data $info = @getimagesize($_FILES['Filedata']['tmp_name']); // Specify directory path for your images directory $upload_directory = $_SERVER[DOCUMENT_ROOT] ."/file_upload/uploads/$loggedinid/$pid/"; $fileLoc="file_upload/uploads/$loggedinid/$pid/"; // Check that the images directory exists if(file_exists($upload_directory)) { // Upload file or return error message information $fileUrl = $fileLoc .$_FILES[Filedata][name]; mysql_query("INSERT INTO `homework` SET `uid`='$loggedin', `pid`='$pid', `url`='$fileUrl', `approved`='0'"); if(!move_uploaded_file($_FILES[Filedata][tmp_name], $upload_directory .$_FILES[Filedata][name])) { $error = "Could not upload file " .$_FILES["Filedata"]["name"] ."<br />" .$_FILES; } } else { mkdir("../uploads/$loggedinid/$pid", 0777); // Upload file or return error message information $fileUrl = $fileLoc .$_FILES[Filedata][name]; mysql_query("INSERT INTO `homework` SET `uid`='$loggedinid', `pid`='$pid', `url`='$fileUrl', `approved`='0'"); if(!move_uploaded_file($_FILES[Filedata][tmp_name], $upload_directory .$_FILES[Filedata][name])) { $error = "Could not upload file " .$_FILES["Filedata"]["name"] ."<br />" .$_FILES; } } if ($info) { $return['width'] = $info[0]; $return['height'] = $info[1]; $return['mime'] = $info['mime']; } } // Output /** * Again, a demo case. We can switch here, for different showcases * between different formats. You can also return plain data, like an URL * or whatever you want. * * The Content-type headers are uncommented, since Flash doesn't care for them * anyway. This way also the IFrame-based uploader sees the content. */ if (isset($_REQUEST['response']) && $_REQUEST['response'] == 'xml') { // header('Content-type: text/xml'); // Really dirty, use DOM and CDATA section! echo '<response>'; foreach ($return as $key => $value) { echo "<$key><![CDATA[$value]]></$key>"; } echo '</response>'; } else { // header('Content-type: application/json'); echo json_encode($return); } ?> The files upload correctly, but I need "uid" and the "pid" variables to carry through. This will then allow me to access the students information from the back-end. The files are uploading fine, I need those variables in there for the rest of the script to work. 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 Hi everyone, I am having trouble with the last() function in xpath . I want to get the text3. The HTML looks like this: Code: [Select] div id="body"> <br> <br> text1 <hr> text2 <br> <br> text3 So far I have: Code: [Select] $lastdata= $simplexml->xpath("//div[@id='body']/following-sibling::node [last()]"); This is not working. I would appreciate any help. Thank you in advance, Bill I am having trouble obtaining the second table in this HTML code: Code: [Select] <!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><html> <head> <meta http-equiv="Pragma" content="no-cache"> <title>Entity Information</title> <link rel="stylesheet" href="documents/CORP/default.css" media="screen" type="text/css"> <link rel="stylesheet" href="documents/CORP/infotable.css" media="screen" type="text/css"> </head> <body> <div class="headings"> <h1 class="dos_heading1">Company Information </h1> <BR> <h2 class="dos_heading2"> </h2> <h3 class="page_heading">Company Information</h3> <p class="DtMsg">The information contained in this database is current through September 10, 2010.</p> </div> <hr noshade width="100%"> <center> <div class="highlight">Selected Company Name: 1 PARK ROW, LLC</div> <table summary="This table contains status information for the selected entity."> <caption> Selected Company Status Information </caption> <tr> <th>Current Company Name:</th> <td>1 PARK ROW, LLC</td> </tr> <tr> <th>Initial Filing Date:</th> <td>JANUARY 22, 1997</td> </tr> <tr> <th>County:</th> <td>NASSAU</td> </tr> <tr> <th>Jurisdiction:</th> <td>NEW JERSEY </td> </tr> <tr> <th>Entity Type:</th> <td>DOMESTIC LIMITED LIABILITY COMPANY</td> </tr> <tr> <th>Current Company Status:</th> <td>ACTIVE </td> </tr> </table> <BR> <table id="tblAddr" summary="This table contains address information for the selected entity."> <caption>Selected Entity Address Information</caption> <tr> <th scope="col" id="c1" class="leftalign"><span class="rmvbold">Address</span></th> </tr> <tr> <td headers="c1"> C/O ELECTRONICS INC.<br> 2355 PARK ROW<br> NEW BRUNSWICK, NEW YORK, 15538 </td> </tr> <tr> <th scope="col" id="c4" class="leftalign">Registered Agent</th> </tr> <tr> <td headers="c1"> NONE </td> </tr> </table> <br> <p style="width:50%"> </p> <div id="divStockContainer"> <h4 id="capStock">*Stock Information</h4> <div id="divStock"> <table id="tblStock" cellpadding="0" cellspacing="6"> <tr> <th># of Shares</th> <th>Type of Stock</th> <th>$ Value per Share</th> </tr> <tr> <td> </td> <td>No Information Available</td> <td> </td> </tr> </table> </div> <p id="pStockBlurb">*Stock information is applicable to domestic business corporations.</p> </div> <div id="divHistNmContainer"> <h4 id="capNmHist">Name History</h4> <div id="divNmHist"> <table id="tblNameHist" cellpadding="0" cellspacing="6"> <tr> <th class="FileDt">Filing Date</th> <th class="NameType">Name Type</th> <th class="CorpName">Company Name</th> </tr> <tr> <td class="FileDt">JAN 22, 1997</td> <td class="NameType">Actual</td> <td class="CorpName">1 PARK ROW, LLC</td> </tr> </table> </div> <p id="pFictName"> </p> </div> </center> </body> </html> <script language='javascript' src='https://a12.alphagodaddy.com/hosting_ads/gd01.js'></script></script> I can get the top part with this: /*** a new dom object ***/ $dom = new domDocument; /*** load the html into the object ***/ $dom->loadHTML($html2); /*** discard white space ***/ $dom->preserveWhiteSpace = false; /*** the table by its tag name ***/ $tables = $dom->getElementsByTagName('table'); /*** get all rows from the table ***/ $rows = $tables->item(0)->getElementsByTagName('tr'); /*** loop over the table rows ***/ foreach ($rows as $row) { /*** get each column by tag name ***/ $cols = $row->getElementsByTagName('td'); /*** echo the values ***/ echo $cols->item(0)->nodeValue.'<br />'; echo $cols->item(1)->nodeValue.'<br />'; echo $cols->item(2)->nodeValue; echo '<hr />'; } } Any help would be appreciated I dont even know where to start to echo the 2nd table in the html. Thanks. I have a database that contains results of fantasy football games. I have a query that returns the results of the games team X played against the other teams in the league. The query works perfect in the database. Results are Quote Opponent Name: America Enforcers Wins Losses Draws 1 1 0 Last Game: Week 2 of 2011: 416.6 - 369.8 the query and the php code cycle thru each team that team X has played and brings up team X's record and the results of the last game played. My problem is that the code stops one team short. So Team X played teams A, B, C, D, E but the code only returns teams A, B, C, D E is left off. I can't for the life of me figure out what silly mistake I made. Code: [Select] <?php include_once('../other/functions.php'); $con = mysql_connect($hostname, $username, $password) OR DIE ('Unable to connect to database! Please try again later.'); $db = mysql_select_db($dbname, $con); $thing = $_GET['thing']; $query = "select selected.teamname AS selected_team, selected_score.score AS selected_score, week.week, year, home_id, ". "target_score.score as target_score, target.teamname as targetname, week.ID ". "from owners as selected ". "JOIN game_scores AS selected_score ON selected.owner_id = selected_score.team_id ". "JOIN game_setup ON game_setup.game_id = selected_score.game_id ". "JOIN game_scores AS target_score ON target_score.game_id = game_setup.game_id AND target_score.team_id != selected_score.team_id ". "JOIN owners AS target ON target.owner_id = target_score.team_id ". "JOIN week ON week.week = game_setup.week ". "WHERE selected.owner_id = $thing ". "and target.active = 1 ". "GROUP BY target.teamname, year, week.ID "; $result = mysql_query($query); $row = mysql_fetch_array($result); $result1 = mysql_query($query); $row1 = mysql_fetch_array($result1); if (!$result) { die('Invalid query: ' . mysql_error()); } $wins=0; $losses=0; $draws=0; $last_target = false; echo '<h2>' . $row1['selected_team'] . ' vs. Active Teams</h2>'; while ($row = mysql_fetch_assoc($result)) { if ($last_target['targetname'] != $row['targetname']) { if ($last_target) { printf(' <table border="1" width="600"> <tr> <th>Opponent Name:</th> <th colspan="2">%s</th> </tr> <tr> <th>Wins</th> <th>Losses</th> <th>Draws</th> </tr> <tr> <td align="center">%d</td> <td align="center">%d</td> <td align="center">%d</td> </tr> <tr> <th>Last Game:</th> <td colspan="2">%s of %s: %.1f - %.1f</td> </tr> </table><br/>', $last_target['targetname'], $wins, $losses, $draws, $last_target['week'], $last_target['year'], $last_target['selected_score'], $last_target['target_score'] ); } $wins = $losses = $draws = 0; } if ($row['selected_score'] < $row['target_score']) ++$losses; elseif ($row['selected_score'] == $row['target_score']) ++$draws; else ++$wins; $last_target = $row; } ?> Any ideas on how to make the magic elvish be good??? Thank you for your time. Hi all, I'm sure I'm making this far more difficult than I need to... I've got an xml document... <library id="1"> <lname>Lib1</name> <book id="1"> <title>book 1</title> <author>Author 1</author> </book> <book id="2"> <title>book 2</title> <author>Author 2</author> </book> </library> I can access the nested elements using xpath like : $result = $xml->xpath('//book'); foreach($result as $books) { echo $books->title; } How would I do this for the attributes? If I specify I want the attributes in the xpath query I can't get at the elements... I'm trying to turn this xml file into a simple relational database... A library table and a book table. So I need the library id (attribute) and the name(nested element) for one insert query - and the book id, title, author and the library id for the other. Anyone got any idea? Cheers John Hello, I recently moved hosts and upgraded to PHP 7.4.10. Suddenly, one of my sites is having issues with XSL views. The software creator claims this is an issue with XSL in PHP. I am unsure of what to check to troubleshoot this. Would anyone have an opinion on my issue? If not, please let me know if I should be posting somewhere else altogether. Thanks in advance - Quote
xmlXPathCompOpEval: function function not found The view.xsl file: Quote
<xsl:value-of select="php:function( 'SobiPro::AlternateLink', $rssUrl, 'application/atom+xml', $sectionName )"/>
Hi all I am trying to get the lat and long properties from the googlemaps geocoding api. $xml=simplexml_load_file($url); if ($xml === false) { echo "Failed loading XML\n"; foreach(libxml_get_errors() as $error) { echo "\t", $error->message; } } else{ $path = $xml->xpath( "/GeocodeResponse/result/geometry/location"); $lat = $path->lat; $lng = $path->lng; echo $lat; echo $lng; $sql1 = "UPDATE tbl_clubs set lat='$lat',lng='$lng' where club_id =$id"; echo $sql1; $result1 = mysqli_query($dbConn,$sql1) or die($mysqli_error($dbConn)); } This is the XML I am using <GeocodeResponse> <status>OK</status> <result> <type>establishment</type> <type>point_of_interest</type> <type>stadium</type> <formatted_address>Aldridge Rd, Perry Barr, Birmingham B42 2ET, UK</formatted_address> <address_component> </address_component> <address_component> </address_component> <address_component> </address_component> <address_component> <long_name>West Midlands</long_name> <short_name>West Midlands</short_name> <type>administrative_area_level_2</type> <type>political</type> </address_component> <address_component> <long_name>England</long_name> <short_name>England</short_name> <type>administrative_area_level_1</type> <type>political</type> </address_component> <address_component> <long_name>United Kingdom</long_name> <short_name>GB</short_name> <type>country</type> <type>political</type> </address_component> <address_component> <long_name>B42 2ET</long_name> <short_name>B42 2ET</short_name> <type>postal_code</type> </address_component> <geometry> <location> <lat>52.5196698</lat> <lng>-1.8986236</lng> </location> <location_type>GEOMETRIC_CENTER</location_type> <viewport> <southwest> <lat>52.5183208</lat> <lng>-1.8999726</lng> </southwest> <northeast> <lat>52.5210188</lat> <lng>-1.8972746</lng> </northeast> </viewport> </geometry>
But I am getting the following response Notice: Trying to get property of non-object in /home/sites/1a/9/95f15f28a6/public_html/results/getLatLng.php on line 22 I am guessing my path is wrong, any guidance would be great |