2

A web development dummy here :) How do I put a php variable inside an html tag? for example, here I want to print each product's name, price, and image (also could you please suggest whether the way I retrieve the image is correct?)

 <?php
$doc = new DOMDocument();
$doc->load('database/products.xml');

$products = $doc->getElementsByTagName("fruit");
foreach ($products as $fruit) {
    $names = $fruit->getElementsByTagName("name");
    $name = $names->item(0)->nodeValue;

    $prices = $fruit->getElementsByTagName("price");
    $price = $prices->item(0)->nodeValue;

    $images = $fruit->getElementsByTagName("image");
    $image = $images->item(0)->nodeValue;

    echo "<b>$name - $price - $image\n</b><br>";


echo'

 <div class="container">
    <a href="p3Apples.html">
       
            <img src="img/'.$image.'" class="item-image">
            <div class=‘iamge-title’>$name</div>
            <div class=‘item-price’> $.$price </div>
            <a href=‘shoppingcart.html’ class=‘b-menu’>
                <img id=‘test’ src=‘img/addToCart.png’> </a>
        </form>
    </a>
    </div>

    ';


};

    ?>
2
  • 1
    Every way you have put PHP inside your HTML tags above, works. They aren't all recommended, but that wasn't really your questions. What exactly, is not working for you? <someHTMLTag><?php $your_variable; ?></someHTMLTag> Commented Aug 15, 2021 at 23:50
  • hi Eirk thanks for answering my question. On VSCode the variables' color did not change, so I assumed there were mistakes somewhere. And the page also gave me a 404 error Commented Aug 16, 2021 at 0:13

1 Answer 1

4

When using ' variables aren't processed, use " in this case

$doc = new DOMDocument();
$doc->load('database/products.xml');
$products = $doc->getElementsByTagName("fruit");

foreach ($products as $fruit) {
    $names = $fruit->getElementsByTagName("name");
    $name = $names->item(0)->nodeValue;
    $prices = $fruit->getElementsByTagName("price");
    $price = $prices->item(0)->nodeValue;
    $images = $fruit->getElementsByTagName("image");
    $image = $images->item(0)->nodeValue;

    echo "<b>$name - $price - $image\n</b><br>";

    echo "
        <div class='container'>
            <a href='p3Apples.html'>
                <img src='img/".$image."' class='item-image'>
                <div class='iamge-title'>$name</div>
                <div class='item-price'> $.".$price."</div>
                <a href='shoppingcart.html' class='b-menu'>
                    <img id='test' src='img/addToCart.png'>
                </a>
            </form>
            </a>
        </div>
    ";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.