peter flanagan
peter flanagan

Reputation: 9790

set background image using php

I am looping through a json object using php and trying to display an image in the json object as a background image of a div.

my json object looks like this:

{
    "1.49514754373E+12": {
        "description": "This is amazing!",
        "fileNames": [
            "3.jpg"
        ],

    }
}

My php file that I am using to display the image in my html looks like this

<?php
    $json = file_get_contents('auction.json');
    $json = json_decode($json);

    foreach($json as $obj){
      echo "<p>" .$obj->description . "</p>";

      //loop through the array of images
      for ($x=0; $x < count($obj->fileNames); $x++) {
         echo "<div style='background-image: url('" .$obj->fileNames[$x]."');'>";
      }

    }
?>

The issue that I am having is that it is setting the html like this

<div style="background-image: url(" 3.jpg');'></div>

Can anyone see what I am doing wrong?

Upvotes: 0

Views: 1457

Answers (1)

Rayann Nayran
Rayann Nayran

Reputation: 1135

I wrapped the style value with double quotes and escaped it with \.

echo "<div style=\"background-image: url('" . $obj->fileNames[$x] . "');\">";

Upvotes: 2

Related Questions