JSON_decode problem with array posted to CodeIgniter

主宰稳场 提交于 2021-02-08 11:41:08

问题


I am certain I am making a simple mistake... but simply can't find it.

Ultimately I am posting a JSON array from an Android app (that part is working), but for the time being I am simply testing between two PHP pages (1: test PHP page with basic form, and 2: the CodeIgniter final destination) Here is what I have:

At the form page:

<form action="bambooinvoice/index.php/api2/newinvoice/4/0/0" method="post">
    <?php 
        $array = array("items"=>array(
            "taxable"=>1, 
            "quantity"=>1, 
            "amount"=>123.99, 
            "work_description"=>"this is a test"));
        $json = json_encode($array);
    ?>
    <input type="hidden" name=json value=<?php $json ?> />
    <input type="submit" name="btnSendForm" value="Send" />
</form>

This creates (which looks good to me):

{"items":{"taxable":1,"Quantity":1,"amount":123.99,"work_description":"this is a test"}}

On the codeIgniter side, I have:

$input = $this->input->post('json');
$items = json_decode($input, TRUE);

$amount = 0;
foreach ($items as $item) // In case there are multiple 'items'
{
    $taxable = (isset($item['taxable']) && $item['taxable'] == 1) ? 1 : 0;

    $invoice_items = array(
        'quantity' => $item['quantity'],
        'amount' => $item['amount'],
        'work_description' => $item['work_description'],
        'taxable' => $taxable
    );

    $this->_addInvoiceItem($invoice_items); //simply adding contents to DB
}

In the end I receive the error: (i have received numerous errors actually in all my tweaking, but this is the one I can't seem to shake)

Message: Invalid argument supplied for foreach()

Edited - to correct a typo.


回答1:


You are using $this->input->post('items') when your form is posting a hidden value named json.

If you var_dump($this->input->post('items')), it should be FALSE or NULL.

Try this in your CI script instead:

$input = $this->input->post('json'); // not 'items'
$items = json_decode($input, TRUE);

// Rest of your code...

That should fix that problem, but you also need to make sure your json data is being sent correctly to begin with! var_dump($_POST) should show you if it's making it to your script in one piece.




回答2:


Try this
<input type="hidden" name=json value='<?=$json?>' /> Or this
<input type="hidden" name=json value='<?=str_replace('\'', '&#039;', $json)?>' />
See htmlspecialchars



来源:https://stackoverflow.com/questions/5148489/json-decode-problem-with-array-posted-to-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!