简体   繁体   中英

read json data in php

I've created a valid JSON object in JavaScript:

[
    {
        "code": "2F-58S",
        "price": "123,13"
    },
    {
        "code": "2F-58S",
        "price": "123,13"
    }
]

I have a problem with reading it in PHP:

$productsArr = json_decode($_GET['object']);
foreach($productsArr as $article)
{
    $html .='<td>'.$article->code.'</td>';
    $html .='<td>'.$article->price.'</td></tr>';
}

I'm getting an error that foreach() loop is not defined as it should be. What am I missing in here?

EDIT:

It seems that I'm not receiving an entire JSON values with the GET method. I'm getting something like: [{"code":"2F-58S","price":"123,13"},{"code":

EDIT2:

JSON object break is happening when reading HTML tags from the object, error is created when you reach this html tag: <p><strong>EnMotion&nbsp;</strong></p>\\n\\n<p><strong>impulse</strong></p>

try this:

$productsArr = file_get_contents('php://input');
foreach($productsArr as $article)
{
    $html .='<td>'.$article->code.'</td>';
    $html .='<td>'.$article->price.'</td></tr>';
}

Try true, with json_decode.

if(!empty($_GET['object'])){
  $productsArr = json_decode($_GET['object'],true);// this will return array
}

~K

Working:

<?php 
 $a = '[
    {
        "code": "2F-58S",
        "price": "123,13"
    },
    {
        "code": "2F-58S",
        "price": "123,13"
    } ]'; 
 $productsArr = json_decode($a,true); 
 print_r($productsArr); 
 $html = ''; 
 foreach($productsArr as $article) { 
    $html .='<td>'.$article['code'].'</td>';
    $html .='<td>'.$article['price'].'</td></tr>';
    echo $html;
} 
?>

Output:

<td>2F-58S</td><td>123,13</td></tr><td>2F-58S</td><td>123,13</td></tr> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM