Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

For example, I have the following code in JSON:

{
    "tag": "img",
    "attr": [
{
        "alt": "text",
        "src": "url",
        "void": "true",
        "all": "true"
}
]
}

What PHP code should I use to echo/print the code above? I tried this:

$arr = array (
    "tag" => "img",
$attr = array (
    "alt" => "text",
    "src" => "url",
    "void" => "true",
    "all" => "true"
)
);

And then:

echo $arr = json_encode($arr);

But I get error. Any ideas?

share|improve this question

closed as off-topic by Bojangles, Rikesh, Jim, Jay Blanchard, Bora Jun 23 at 12:47

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example." – Bojangles, Rikesh, Jay Blanchard, Bora
If this question can be reworded to fit the rules in the help center, please edit the question.

4  
Which error do you get. My bet is php5-json isn't installed –  Bojangles Jun 23 at 12:44
    
What error did you get? Can you specify the full, exact stacktrace? We needs it. –  Unihedron Jun 23 at 12:44

2 Answers 2

up vote 1 down vote accepted

Your array declaration is wrong. It should be:

$arr = array (
    "tag" => "img",
    "attr" => array (
        "alt" => "text",
        "src" => "url",
        "void" => "true",
        "all" => "true"
    )
);
share|improve this answer
1  
You would be surprised to find out that it works even using $attr =, but instead of using attr as an index, you will get a numerical value instead. I have no idea why it works this way. –  Ohgodwhy Jun 23 at 12:48
    
@Ohgodwhy Huh, you're right. Definitely not what I would have expected. –  Jim Jun 23 at 12:51
2  
@Ohgodwhy Think it works because the expression is an assignment. So $attr gets the value of the array which is then returned as a value, meaning it has no key. –  Jim Jun 23 at 12:52
    
Looks right - ideone.com/f9zyHd –  Harsh Moorjani Jun 23 at 12:55

Change to -

$arr = array (
    "tag" => "img",
    "attr" => array (
        "alt" => "text",
        "src" => "url",
        "void" => "true",
        "all" => "true"
    )
);

ie. $attr = array ( to "attr" => array (

share|improve this answer
    
While this is true, it doesn't generate an error in OP's original format. check this Ideone –  Ohgodwhy Jun 23 at 12:49

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