Php does not have data (empty) when reading json.

Source: Internet
Author: User

Php does not have data (empty) when reading json.

When PHP is used to call some json interface files, if file_get_contents is used to obtain the page json data

After json_decode () is used for parsing, data cannot be normally output. The returned value is null.

This is because the data obtained by file_get_contents in php contains three BOM characters that cannot be seen before it. It still cannot be solved if php transcoding or header encoding is no BOM

One feasible method is:

<? Php
$ Str = file_get_contents ('json interface address'); // obtain the page address $ str = substr ($ str, 3 ); // due to a php problem, the data obtained by file_get_contents contains three BOM characters that cannot be seen before it. Use the substr function to extract the content after the third character $ json = json_decode ($ str, true ); // parse the json code and return the array value echo $ json ['motd ']; // output the motd array in json with array

Another type:

<? Php $ str = file_get_contents ('json interface address'); // obtain the page address $ json = json_decode (trim ($ str, chr (239 ). chr (1, 187 ). chr (191), true); // chr (239 ). chr (1, 187 ). chr (191) forms the bom header of the utf8 file during output, and then uses the trim function to remove print_r ($ json); // outputs json in array

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.