1

I am trying to count the length of an array that I converted from JSON using json_decode in php but it is not working for some reason. This is my current code. The JSON list contains an array that has 10,000 items. I am pretty sure that I am missing something. Any help will be greatly appreciated.

PHP

<?php
$fl = file_get_contents($somepath);
$text = json_decode($fl, true);

$len = count($text["alphalist"]);

echo $len;
?>

JSON

{
"alphalist": [{
        "a": "alphabet1."
    }, {
        "b": "alphabet2."
    }, {
        "c": "alphabet3."
    }, {
        "d": "alphabet4."
    }, {
        "e": "alphabet5."
    }
    ....
    {
        "zzzzz": "alphabet10000."
    }
]
}
10
  • What does echo $len; returns so far? Commented May 31, 2015 at 5:28
  • it returns 0 when I tested it Commented May 31, 2015 at 5:29
  • I have just tested your code and json_decoding your JSON string returns 5 elements in the array. Are you sure you are posting the full code? Commented May 31, 2015 at 5:31
  • Sorry. You are right. That is not the full code. The entire json file has 20000 lines. I validated it with online verifiers but I am not sure what the problem is. Commented May 31, 2015 at 5:35
  • 1
    Please post the solution to your problem so it can help others and accept the answer within two days :) Commented May 31, 2015 at 5:54

1 Answer 1

1

The answer was actually here in response to another similar question.

PHP not converting JSON using 'json_decode()'

So after some testing with user D4V1D, it turns out that the problem was due to the PHP function json_decode not working because it wasn't in the UTF-8 format. The workaround for this is

$fl = file_get_contents($somepath);
$text = json_decode(utf8_encode($fl), true);
$len = count($text["alphalist"]);

Now $len will give the correct array length. If there is any error or improvement to be made in my explanation, just place it in the comments and I will correct it accordingly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.