2

I added this line in my custom template to display the image:

<?php echo $article->images; ?>

And I got this as a result:

{"image_intro":"images\/articles\/liang2.jpg","float_intro":""}

So, I tried to display the image using this:

<img src="<?php echo $images->image_intro; ?>" >

The output is this: <img src=""> instead of <img src="images/articles/liang2.jpg">

Where am I going wrong?

1
  • What exactly you are trying to do and where you are doing it?
    – FFrewin
    Dec 2, 2015 at 8:14

2 Answers 2

2

The image is part of a JSON encoded string, which you saw by echoing $article->images;.

Therefore, before trying to display the image, you'll need to decode the string first, like so:

$images = json_decode($article->images);
1
  • 2
    Your answer would be better if you included some explanations.
    – FFrewin
    Dec 2, 2015 at 6:11
2

You're very close. You are just missing the step of decoding the $article->images json string.

Like "A. Snake" correctly said, you have to convert the JSON string into an object by which you can access each key and value.

PHP's manual page for the json_decode() function

So this will work:

$images = json_decode($article->images);
echo $images->image_intro

Or you can perform it in a single line within your tag like this:

<img src="<?php echo json_decode($article->images)->image_intro; ?>" >

To write a variable declaration using the decoded the JSON string, use the following syntax:

$value = $JSON_object->key

See the php manual for more specifications and examples.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.