-2

I have the following JSON from which I need to extract the URL of the icon in PHP:

product 
  id    3
  name  "ETC Source 4 19deg"
  type  "Product"
  tax_class_id  2
  rental_revenue_group_id   1
  sale_revenue_group_id 2
  created_at    "2017-10-02T10:50:32.239Z"
  updated_at    "2017-10-02T16:48:44.844Z"
  custom_fields {}
  product_group {…}
  tax_class {…}
  icon  
    id  1
    iconable_id 3
    iconable_type   "Item"
    image_file_name "Source_4_fixed.jpg"
    url "https://s3.amazonaws.com/current-rms/899701e0-898a-0135-ef0d-0a9ca217e95b/icons/1/original/Source_4_fixed.jpg"
    thumb_url   "https://s3.amazonaws.com/current-rms/899701e0-898a-0135-ef0d-0a9ca217e95b/icons/1/thumb/Source_4_fixed.jpg"
    created_at  "2017-10-02T16:48:44.747Z"
    updated_at  "2017-10-02T16:48:44.747Z"

I have used the following to get the top level info:

$ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response);

    return $data;

public function getProduct( $id )
{
    $data = $this->query('products/' . $id);
    return $data->product;
}

$html .= '<div class="row">';
    $html .= 'Product Name is:' . $product->name;
    $html .= '</div>';
    echo $html;

Any help appreciated.

Chris

  • 1
    Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – Jonnix Mar 04 '18 at 10:32
  • 1
    Though what you've given us at the top isn't JSON. – Jonnix Mar 04 '18 at 10:33
  • The datas given are not given, please provide a reproducible example. Also, explain really what's wrong in what you are trying. – Anthony Mar 04 '18 at 14:23

1 Answers1

0

What you posted in your question is not a JSON format but it looks like a striped one. However, to access to an element you just need to down through it like a tree, in your case you want URL so it becomes:

product -> icon -> url

And the PHP version:

echo $data->icon->url;

You can also convert the JSON format to an array and then access to elements like this:

{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, TRUE); // passing true parameter
    return $data;
}


echo $data['product']['icon']['url'];

For more explination and examples read those answers of this question 'How do I extract data from JSON with PHP?'.

H Aßdøµ
  • 2,925
  • 4
  • 26
  • 37