Friday, February 19, 2016

Web Dev: PHP Scraping & Quizes

In addition to taking a beginner-intermediate course on Udemy for PHP and MySQL, I've also been reviewing some projects I created in Rob Percival’s tutorial, The Complete Web Developer’s Course. My first run-through the PHP projects ended with quite a few errors, so I wanted to repeat the tutorials and create working demos. One of those projects I discussed last time –the PHP contact form.


This month I started with fixing up a PHP Weather predictor, in which I used a scraping technique with PHP. Scraping, in short, is when you take content from one website. In this case, I took weather predictions from weather-forecast.com and equipped with Bootstrap styles. The background image is from Unsplash.I used the following code to accomplish this:

<?phperror_reporting(0);
$city=$_GET['city'];
$city=str_replace(" ", "", $city);
$contents=file_get_contents("http://www.weather-forecast.com/locations/$city/forecasts/latest"); 
preg_match('/<span class="phrase">(.*?)<\/s/', $contents,$matches);print_r($matches[1]);
?>
The error_reporting function was very important, as before I added it in, whenever the used typed something other than a city, the PHP error showed up in the alert box. The preg_match piece searches for the code that I need (AKA, the paragraph labeled “phrase”), and then I simply call the variable that I want to see in the alert box, which I defined earlier in the code.

Another issue I had was figuring out delimiters, which differentiates the data form the rest of the code.

The second project that I have worked on (also using Bootstrap styling) is creating an online Quiz, which I can add to as I progress through my current tutorial. My goal is to eventually integrate a database into the code to replicate an online application. For now, however, I started with a sample quiz question that returns results. The code, luckily, wasn’t too difficult, as it was primarily assigning variables and calling them in a div.

I’m finishing up the PHP Fundamentals section from the Infinite Skill’s course on PHP and MYSQL, and then I’ll head into the more advanced functions. I still have the goal of being able to put together an ecommerce site and a forum from scratch by the end of the year. So far the progress has been on schedule.

No comments:

Post a Comment