I understand there are other similar posts about this, I am going out of my wits end here.
I have a few files with some JSON (all valid according to online validators, eg. jsonlint) - see EDIT below.
$contents = file_get_contents(DATA_PATH.'/'.$type.'.json');
$data = json_decode($contents, true);
echo var_dump($data);
Returns NULL
If I echo $contents, I do get output.
I'm not sure what is wrong? I understand file_get_contents gets it into a string, however, how do I get it in a valid JSON? Would using fopen() be any different?
I even added the JSON to a variable but had the same outcome... I must be stupid.
Note: Most JSON I'll get will be from an API, these file-based JSONs are for testing purposes.
Thanks.
EDIT: Sample json
{
"data": [{
"id": 1,
"name": "Albania",
"alpha2code": "AL",
"alpha3code": "ALB",
"capital": "Tirana",
"flag": "https://cdn.elenasport.io/flags/svg/1",
"region": "Europe",
"subregion": "Southern Europe",
"timezones": [
"UTC+01:00"
]
},
{
"id": 3,
"name": "Algeria",
"alpha2code": "DZ",
"alpha3code": "DZA",
"capital": "Algiers",
"flag": "https://cdn.elenasport.io/flags/svg/3",
"region": "Africa",
"subregion": "Northern Africa",
"timezones": [
"UTC+01:00"
]
}]
}
Your file might have a UTF-8 BOM which is not copied when you copy-and-paste your sample JSON to a (web based) validator. It's an invisible mark at the beginning of your file.
If you run echo bin2hex(file_get_contents(DATA_PATH.'/'.$type.'.json')) your file should begin with 7b, which is a {.
If it starts with efbbbf and then a 7b, there is a BOM. Either strip it out yourself or re-save your JSON without one using a text editor like Sublime Text which allows you to configure that.
Related
I already did my research first, but some topics didn't solve my issue and some quite different from what issue I have. I have a JSON that didn't print out the entire data and as upon checking the culprit is the newline when it was a value (it is my first time knowing it, my bad).
<?php
$jsn = <<<_JSON
{
"name": "Editorial",
"links": "default",
"data": [
{
"Status": "Pending",
"Tags": "Documentation",
"Info": "all documentation to be ready by Friday"
},
{
"Status": "Published",
"Tags": "Pros and Cons Limits",
"Info": "documentations about-Realtime\n-Speed per sec\n-API Limit"
}
]
}
_JSON;
$data = json_decode($jsn, true);
$output= $data['links'];
echo $output;
It will not print any output as the \n was there. So I was planning to do in the future, if they tried to use a newline, I will just temporary change the \n to other characters and decode it back. And that's where I'm having a hard time.
As testing it wasn't working for me.. Converting it back and show in textarea.
$txt = "Documentations about%2Realtime%2Speed per sec%2API Limit";
$value = str_replace("%2", '\n', $txt);
$textArea = '<textarea rows="4">'.nl2br($value).'</textarea>';
echo $textarea;
//output
//documentations about\nRealtime\nSpeed per sec\nAPI Limit
If anyone can help me in your spare time, I really appreciate it.. Thanks in advance.
I've read through all the questions I could find on here, and but none of the examples I've found have worked, current have a script returning the following json:
{
"clickid": "24231527",
"geo_data": {
"country_code": "FR",
"state": "Paris",
"city": "Paris",
"currency_symbol": "\u0080",
"currency_code": "EUR"
}
}
I've tried all of the following, but I keep getting either a square box, or question mark when I try to convert it to UTF-8:
header('content-type:text/html;charset=utf-8');
$data = json_decode($output, false, JSON_UNESCAPED_UNICODE);
$geo_data->{"currency_symbol"} = utf8_encode($geo_data->{"currency_symbol"});
Every combination I try to get it to print the € is either returning a box (withont the encode) or a ? (with the encode).
I am trying to add a JSON script to a php file in my sites admin. My goal is to have the JSON run when the order status is change to 3 (shipped).
I am pretty sure I am going about this all wrong but I am not sure what to do yet. here is my code:
if ( ($check_status['orders_status'] != $status) && $check_status['orders_status'] == 3) { ?>
<script>
POST https://api.yotpo.com/oauth/token
{
"client_id": "### Your client_id ###",
"client_secret": "### Your client_secret ###",
"grant_type": "client_credentials"
}
POST https://api.yotpo.com/myapi/purchases
{
"validate_data": true,
"platform": "general",
"utoken": "### YOUR UTOKEN ###",
"email": "client#abc.com",
"customer_name": "bob",
"order_id": "order_1",
"order_date": "2010-10-14",
"currency_iso": "USD",
"products": {
"SKUaaa12": {
"url": "http://example_product_url1.com",
"name": "product1",
"image": "http://images2.fanpop.com/image/photos/13300000/A1.jpg",
"description": "this is the description of a product",
"price": "100",
"specs": {
"upc": "USB",
"isbn": "thingy"
},
"product_tags": "books"
}
}
}
</script>
<?php } ?>
First of all, there is nothing in my code that says hey, this is JSON besides the tag.
do I need to have the json in a sepearate json file? Or do I need to convert this script to php?
First of all, Nikita is correct that JSON does not run - it is not script. It is a standardized way to store information.
PHP has native JSON handling functions and can easily take existing objects or arrays and convert them to JSON.
<?php
$json = json_encode($my_data);
?>
<input type="hidden" name="post_data" <?php echo 'value="'.$json.'" ?> />
Then when you send this variable $json to the next page, you'll unpack it like so
$my_data = json_decode($_POST['post_data']);
This is a pure PHP implementation, though JavaScript does nice functions to stringify to/from json as well.
I assume some of you might be already rolling their eyes since my topic has been dealt with so often in this forum. However, I haven't found any solution yet in this forum.
I want to parse a JS Object to a receiving PHP Site via JSON. I already read numerous times about the right parameters for the XMLHttpRequest-Header and its impact on the PHP part. I tried the very same solutions given in several other forums, but IT SIMPLY DOESN'T WORK for me. I've been working on this whole issue for four month now. I really need some advice.
Here is my JSON encoding JS Script:
function saveToDB(knotItems) {
var txtobj = knotItems;
var json = JSON.stringify(txtobj);
var url = "http://localhost/projektplaner/tools/DBConnection/writeFileToDB.php";
rq = new XMLHttpRequest();
rq.open("post", url, true);
rq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
rq.send("project=" + json);
rq.onreadystatechange = window.open(url);
}
This is the JS-generated object array knotItems after being stringified by JSON:
[{
"rank": 1,
"name": "Baugrube",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "19.5.2016",
"faz_timestamp": 1463680336402,
"d": "2",
"parallelTask": "seriell",
"fez": ["2016-05-21T17:52:16.402Z", "21.5.2016", "NaN2"],
"fez_dateObj": "2016-05-21T17:52:16.402Z",
"fez_string": "21.5.2016"
}, {
"rank": 2,
"name": "Kellerwände",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "21.5.2016",
"faz_timestamp": 1463853136402,
"d": "4",
"parallelTask": "seriell",
"fez": ["2016-05-25T17:52:16.402Z", "25.5.2016", "NaN4"],
"fez_dateObj": "2016-05-25T17:52:16.402Z",
"fez_string": "25.5.2016"
}, {
"rank": 3,
"name": "Kellerdecke",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "25.5.2016",
"faz_timestamp": 1464198736402,
"d": "5",
"parallelTask": "seriell",
"fez": ["2016-05-30T17:52:16.402Z", "30.5.2016", "NaN5"],
"fez_dateObj": "2016-05-30T17:52:16.402Z",
"fez_string": "30.5.2016"
}]
The reason I post the variable content is to show that all object keys are in double quotes, as required by PHP's json_decode.
This is my PHP receiving script:
if(isset($_POST['project']))
{
echo json_decode($_POST['project'],true);
}
else
{
echo "Keine Daten"; // No Data
}
This is the parameter payload that can be seen via Firebug analysis:
project:"[{"rank":1,"name":"Baugrube","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"19.5.2016","faz_timestamp":1463680336402,"d":"2","parallelTask":"seriell","fez":["2016-05-21T17:52:16.402Z","21.5.2016","NaN2"],"fez_dateObj":"2016-05-21T17:52:16.402Z","fez_string":"21.5.2016"},{"rank":2,"name":"Kellerwände","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"21.5.2016","faz_timestamp":1463853136402,"d":"4","parallelTask":"seriell","fez":["2016-05-25T17:52:16.402Z","25.5.2016","NaN4"],"fez_dateObj":"2016-05-25T17:52:16.402Z","fez_string":"25.5.2016"},{"rank":3,"name":"Kellerdecke","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"25.5.2016","faz_timestamp":1464198736402,"d":"5","parallelTask":"seriell","fez":["2016-05-30T17:52:16.402Z","30.5.2016","NaN5"],"fez_dateObj":"2016-05-30T17:52:16.402Z","fez_string":"30.5.2016"}]"
HTTP Status Code is always 200 (OK).
And this is what I get from the PHP File.
Notice: Undefined index: project in C:\xampp\htdocs\projektplaner\tools\DBConnection\writeFileToDB.php on line 7
Keine Daten
I don't want to sound melodramatic or anything, but I'm about to go ape. I just can't see what the hell is wrong. Could it be a Server configuration issue?
I really, really appreciate your help.
Thank you very much in advance.
I am using PHP on shared server to access external site via API that is returning JSON containing 2 levels of data (Level 1: Performer & Level 2: Category array inside performer). I want to convert this to multidimensional associative array WITHOUT USING json_decode function (it uses too much memory for this usage!!!)
Example of JSON data:
[
{
"performerId": 99999,
"name": " Any performer name",
"category": {
"categoryId": 99,
"name": "Some category name",
"eventType": "Category Event"
},
"eventType": "Performer Event",
"url": "http://www.novalidsite.com/something/performerspage.html",
"priority": 0
},
{
"performerId": 88888,
"name": " Second performer name",
"category": {
"categoryId": 88,
"name": "Second Category name",
"eventType": "Category Event 2"
},
"eventType": "Performer Event 2",
"url": "http://www.novalidsite.com/somethingelse/performerspage2.html",
"priority": 7
}
]
I have tried to use substr and strip the "[" and "]".
Then performed the call:
preg_match_all('/\{([^}]+)\}/', $input, $matches);
This gives me the string for each row BUT truncates after the trailing "}" of the category data.
How can I return the FULL ROW of data AS AN ARRAY using something like preg_split, preg_match_all, etc. INSTEAD of the heavy handed calls like json_decode on the overall JSON string?
Once I have the array with each row identified correctly, I CAN THEN perform json_decode on that string without overtaxing the memory on the shared server.
For those wanting more detail about json_decode usage causing error:
$aryPerformersfile[ ] = file_get_contents('https://subdomain.domain.com/dir/getresults?id=1234');
$aryPerformers = $aryPerformersfile[0];
unset($aryPerformersfile);
$mytmpvar = json_decode($aryPerformers);
print_r($mytmpvar);
exit;
If you have a limited amount of memory, you could read the data as a stream and parse the JSON one piece at a time, instead of parsing everything at once.
getresults.json:
[
{
"performerId": 99999,
"name": " Any performer name",
"category": {
"categoryId": 99,
"name": "Some category name",
"eventType": "Category Event"
},
"eventType": "Performer Event",
"url": "http://www.novalidsite.com/something/performerspage.html",
"priority": 0
},
{
"performerId": 88888,
"name": " Second performer name",
"category": {
"categoryId": 88,
"name": "Second Category name",
"eventType": "Category Event 2"
},
"eventType": "Performer Event 2",
"url": "http://www.novalidsite.com/somethingelse/performerspage2.html",
"priority": 7
}
]
PHP:
$stream = fopen('getresults.json', 'rb');
// Read one character at a time from $stream until
// $count number of $char characters is read
function readUpTo($stream, $char, $count)
{
$str = '';
$foundCount = 0;
while (!feof($stream)) {
$readChar = stream_get_contents($stream, 1);
$str .= $readChar;
if ($readChar == $char && ++$foundCount == $count)
return $str;
}
return false;
}
// Read one JSON performer object
function readOneJsonPerformer($stream)
{
if ($json = readUpTo($stream, '{', 1))
return '{' . readUpTo($stream, '}', 2);
return false;
}
while ($json = readOneJsonPerformer($stream)) {
$performer = json_decode($json);
echo 'Performer with ID ' . $performer->performerId
. ' has category ' . $performer->category->name, PHP_EOL;
}
fclose($stream);
Output:
Performer with ID 99999 has category Some category name
Performer with ID 88888 has category Second Category name
This code could of course be improved by using a buffer for faster reads, take into account that string values may themselves include { and } chars etc.
You have two options here, and neither of them include you writing your own decoder; don't over-complicate the solution with an unnecessary work-around.
1) Decrease the size of the json that is being decoded, or
2) Increase the allowed memory on your server.
The first option would require access to the json that is being created. This may or may not be possible depending on if you're the one originally creating the json. The easiest way to do this is to unset() any useless data. For example, maybe there is some debug info you won't need, so you can do unset($json_array['debug']); on the useless data.
http://php.net/manual/en/function.unset.php
The second option requires you to have access to the php.ini file on your server. You need to find the line with something like memory_limit = 128M and make the 128M part larger. Try increasing this to double the value already within the file (so it would be 256M in this case). This might not solve your problem though, since large json data could still be the core of your problem; this only provides a work-around for inefficient code.