I’m a beginning programmer who is trying to capture data from this source
Here’s the specific part I’m trying to capture:
<ul class="ingredient-wrap">
<li id="liIngredient" data-ingredientid="3914" data-grams="907.2">
<label>
<span class="checkbox-formatted"><input id="cbxIngredient" type="checkbox" name="ctl00$CenterColumnPlaceHolder$recipeTest$recipe$ingredients$rptIngredientsCol1$ctl01$cbxIngredient" /></span>
<p class="fl-ing" itemprop="ingredients">
<span id="lblIngAmount" class="ingredient-amount">2 pounds</span>
<span id="lblIngName" class="ingredient-name">ground beef chuck</span>
</p>
</label>
</li>
<li id="liIngredient" data-ingredientid="5838" data-grams="454">
<label>
<span class="checkbox-formatted"><input id="cbxIngredient" type="checkbox" name="ctl00$CenterColumnPlaceHolder$recipeTest$recipe$ingredients$rptIngredientsCol1$ctl02$cbxIngredient" /></span>
<p class="fl-ing" itemprop="ingredients">
<span id="lblIngAmount" class="ingredient-amount">1 pound</span>
<span id="lblIngName" class="ingredient-name">bulk Italian sausage</span>
</p>
</label>
</li>
<li id="liIngredient" data-ingredientid="10429" data-grams="1278">
<label>
<span class="checkbox-formatted"><input id="cbxIngredient" type="checkbox" name="ctl00$CenterColumnPlaceHolder$recipeTest$recipe$ingredients$rptIngredientsCol1$ctl03$cbxIngredient" /></span>
<p class="fl-ing" itemprop="ingredients">
<span id="lblIngAmount" class="ingredient-amount">3 (15 ounce) cans</span>
<span id="lblIngName" class="ingredient-name">chili beans, drained</span>
</p>
</label>
</li>
Each li contains two sets of words, for example: 3 (15 ounce) cans and chili beans, drained I’m trying to use a foreach loop to grab the two set of words from each li, and then combine and save into a database.
Here’s my code:
foreach($html->find(".ingredient-wrap", 0)->children as $e){
$ingredients = $e->plaintext;
echo trim($ingredients);
$hostname = 'localhost';
$username = '********';
$password = '*******';
$conn = new PDO("mysql:host=$hostname;dbname=*********", $username, $password);
$sql = ("INSERT INTO ingredients (recipe_id, ingredientname) VALUES (?, ?)");
$q = $conn->prepare($sql);
$q->execute(array($recipe_id,$ingredients));
}
The problem with this is that after inserting into the database, the value for each ingredientname is …, even though if you echo out echo $ingredients."<br/>" you are presented with a list of the combined word with a space after it.
Thanks for any and all help! If you have any questions or need more clarifying, I’m here to reply!
Getting a “list” is normal. You’re using
->innertextto get the ingredients. Essentially you’re doingstriptags()on the html that contains the ingredients, leaving you with just some bare text. You should be looping over each ingredient tag separately.