У меня есть библиотека рецептов. Я хочу получить ответ JSON, истинный или ложный, когда мы получим ответ. если есть ответ, то статус равен 1, что верно, а когда мы не получаем ответ, он равен 0. Я получаю ответ, но хочу поставить статус в разделе ингредиентов, когда список пуст, статус равен 0 и наоборот. Этот статус на всем респоне, который я хочу, просто в списке ингредиентов. Если список ингредиентов пуст, тогда ответ равен 0, и если список ингредиентов доступен, тогда ответ равен 1.
Вот код recipe.php
<?php
class RecipeParser_Recipe {
public $title = '';
public $description = '';
public $credits = '';
public $notes = '';
public $yield = '';
public $source = '';
public $url = '';
public $categories = array();
public $photo_url = '';
public $_parser = '';
// These times are all stored as minutes.
public $time = array(
'prep' => 0,
'cook' => 0,
'total' => 0
);
// Ingredients and instructions are lists of sections, each section
// contains a name and a list of ingredients.
public $ingredients;
public $instructions;
public function __construct() {
$this->resetIngredients();
$this->resetInstructions();
}
public function getArray() {
$arr = array(
'title' => $this->title,
'description' => $this->description,
'credits' => $this->credits,
'notes' => $this->notes,
'yield' => $this->yield,
'source' => $this->source,
'url' => $this->url,
'categories' => $this->categories,
'photo_url' => $this->photo_url,
'time' => $this->time,
'ingredients' => $this->ingredients,
'instructions' => $this->instructions,
'_parser' => $this->_parser,
);
return $arr;
}
public function getJson() {
return json_encode($this->getArray());
}
public function resetIngredients() {
$this->ingredients = array(array("name" => "", "list" => array()));
}
public function resetInstructions() {
$this->instructions = array(array("name" => "", "list" => array()));
}
public function addIngredientsSection($name="") {
if (!$name) {
return;
}
// When adding a new section, make sure the previous section was used.
$index = count($this->ingredients);
if ($index > 0
&& empty($this->ingredients[$index - 1]['name'])
&& !count($this->ingredients[$index - 1]['list'])
) {
$index--;
}
$name = trim($name);
$this->ingredients[$index] = array('name' => $name, 'list' => array());
}
public function addInstructionsSection($name="") {
if (!$name) {
return;
}
// When adding a new section, make sure the previous section was used.
$index = count($this->instructions);
if ($index > 0
&& empty($this->instructions[$index - 1]['name'])
&& !count($this->instructions[$index - 1]['list'])
) {
$index--;
}
$name = trim($name);
$this->instructions[$index] = array('name' => $name, 'list' => array());
}
public function appendIngredient($str) {
if (!empty($str)) {
$this->ingredients[count($this->ingredients)-1]['list'][] = $str;
}
}
public function appendInstruction($str) {
if (!empty($str) && !self::isIgnoredInstruction($str)) {
$this->instructions[count($this->instructions)-1]['list'][] = $str;
}
}
public function isIgnoredInstruction($str) {
if (preg_match("/^Reprinted with permission/i", $str)) {
return true;
} else if (preg_match("/per serving\:.*calories/i", $str)) {
return true;
}
return false;
}
public function appendCategory($str) {
if (!empty($str)) {
$this->categories[count($this->categories)] = $str;
}
}
}
scrapper.php
<code> <?php
$url = isset($_REQUEST["url"]) ? $_REQUEST["url"] : '';
require_once dirname(__FILE__) . '/bootstrap.php';
//$url ="http://www.bonappetit.com/recipes/quick-recipes/2010/02 /chai_spiced_hot_chocolate";
//$url ="https://www.foodnetwork.com/recipes/fried-chicken-recipe10-3381583";
//$url ="https://www.dietdoctor.com/recipes/keto-pizza";
$recipe = RecipeParser::parse(file_get_contents($url), $url);
//echo '<pre>';
//print_r($recipe);
// echo '
';if ($ recipe) {// $ recipe ['status'] = 'true';// $ recipe ['message'] = "Данные найдены";$ recipe-> status = 1;$ recipe-> message = "Данные найдены";} else {// $ recipe ['status'] = 'false';// $ recipe ['message'] = "Данные не найдены";$ recipe-> status = 0;$ recipe-> message = "Данные не найдены";} header ('Content-type: application / json');echo json_encode ($ recipe);?>
Ответ в формате JSON
{
"title": "Keto Pizza – The Best Pizza Recipe with Video – Diet Doctor",
"description": "",
"credits": "Anne Aobadia",
"notes": "",
"yield": "2 servings",
"source": null,
"url": "https://www.dietdoctor.com/recipes/keto-pizza",
"categories": [],
"photo_url": "https://i.dietdoctor.com/wp-content/uploads/2016/01/keto_pizza_v.jpg?auto=compress%2Cformat&w=1600&h=1067&fit=crop",
"_parser": "StructuredData",
"time": {
"prep": 5,
"cook": 25,
"total": 30
},
"ingredients": [
{
"name": "",
"list": [
"4 eggs",
"11 oz. shredded cheese, preferably mozzarella or provolone",
"3 tbsp unsweetened tomato sauce",
"1 tsp dried oregano",
"1 1/2 oz. pepperoni",
"olives (optional)",
"2 oz. leafy greens",
"4 tbsp olive oil",
"sea salt",
"ground black pepper"
]
}
],
"instructions": [
{
"name": "",
"list": [
"Preheat the oven to 400°F (200°C).",
"Start by making the crust. Crack eggs into a medium-sized bowl and add shredded cheese. Give it a good stir to combine.",
"Use a spatula to spread the cheese and egg batter on a baking sheet lined with parchment paper. You can form two round circles or just make one large rectangular pizza. Bake in the oven for 15 minutes until the pizza crust turns golden. Remove and let cool for a minute or two.",
"Increase the oven temperature to 450°F (225°C).",
"Spread tomato sauce on the crust and sprinkle oregano on top. Top with cheese and place the pepperoni and olives on top.",
"Bake for another 5-10 minutes or until the pizza has turned a golden brown color.",
"Serve with a fresh salad on the side."
]
}
],
"status": 1,
"message": "Data found"