<?php
class Restaurant
{
private $url;
private $name;
private $xpaths = array();
public function getName()
{
return $this->name;
}
public function getUrl()
{
return $this->url;
}
public function getXpaths()
{
return $this->xpaths;
}
function __construct($name, $url, $xpaths)
{
if (empty($url) || empty($xpaths)) {
throw new InvalidArgumentException("All argument are required");
}
$this->name = $name;
$this->url = $url;
if (is_string($xpaths)) {
$this->xpaths[] = $xpaths;
} else if (is_array($xpaths)) {
$this->xpaths = $xpaths;
} else {
throw new InvalidArgumentException("Xpaths must be string or array");
}
}
}
class Parser {
private $restaurants = array();
function __construct($restaurants)
{
if (empty($restaurants) || !is_array($restaurants)) {
throw new InvalidArgumentException("Array argument required");
}
$this->restaurants = $restaurants;
}
public function parse()
{
foreach ($this->restaurants as $restaurant) {
$source = file_get_contents($restaurant->getUrl());
if ($source === false) {
throw new RuntimeException("Can't read source address: " . $restaurant->getUrl());
}
$dom = new DOMDocument();
@$dom->loadHTML($source);
$xpath_obj = new DOMXPath($dom);
echo("Restaurant: <a href='{$restaurant->getUrl()}'>" . $restaurant->getName() . "</a><br>\n");
foreach ($restaurant->getXpaths() as $name => $xpath) {
$found = $xpath_obj->query($xpath);
if ($found === false || $found->length === 0) {
continue;
}
echo "<b>$name</b>";
$exists = false;
foreach ($found->item(0)->childNodes as $elem) {
$meal = trim($elem->nodeValue);
if (!empty($meal)) {
echo("\t<br>$meal\n");
$exists = true;
}
}
if (!$exists) {