Having an issue with getting unicode to parse with json_encode - php

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).

Related

Scraping websites with PHP

I'm trying to scrap information directly from the maersk website.
Exemple, i'm trying scraping the information from this URL https://www.maersk.com/tracking/221242675
I Have a lot of tracking nunbers to update every day on database, so I dicided automate a little bit.
But, if have the following code, but its saying that need JS to work. I alredy even tryed with curl, etc.
But nothing work. Any one know another way?
I tryed the following code:
<?php
// ------------ teste 14 ------------
$html = file_get_contents('https://www.maersk.com/tracking/#tracking/221242675'); //get the html returned from the following url
echo $html;
$ETAupdate = new DOMDocument();
libxml_use_internal_errors(TRUE); //disable libxml errors
if(!empty($html)){ //if any html is actually returned
$ETAupdate->loadHTML($html);
libxml_clear_errors(); //remove errors for yucky html
$ETA_xpath = new DOMXPath($ETAupdate);
//get all the h2's with an id
$ETA_row = $ETA_xpath->query('//strong');
if($ETA_row->length > 0){
foreach($ETA_row as $row){
echo $row->nodeValue . "<br/>";
}
}
}
?>
You need to scrape the data directly from their API requests, rather than trying to scrape the page URL directly (Unless you're using something like puppeteer, but I really don't recommend that for this simple task)
I took a look at the site and the API endpoint is:
https://api.maersk.com/track/221242675?operator=MAEU
This will return a JSON-formatted response which you can parse and use to extract the details. It'll also give you a much easier method to access the data rather than parsing the HTML. Example below.
{
"tpdoc_num": "221242675",
"isContainerSearch": false,
"origin": {
"terminal": "YanTian Intl. Container Terminal",
"geo_site": "1PVA2R05ZGGHQ",
"city": "Yantian",
"state": "Guangdong",
"country": "China",
"country_code": "CN",
"geoid_city": "0L3DBFFJ3KZ9A",
"site_type": "TERMINAL"
},
"destination": {
"terminal": "DCT Gdansk sa",
"geo_site": "02RB4MMG6P32M",
"city": "Gdansk",
"state": "",
"country": "Poland",
"country_code": "PL",
"geoid_city": "3RIGHAIZMGKN3",
"site_type": "TERMINAL"
},
"containers": [ ... ]
}

Convert newline in JSON and print in textarea using PHP

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.

Valid JSON from text file

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.

Write a script which decodes the Following JSON String. Any idea how to get pass the Address part?

im trying to do this json decoding my professor suggested i try, but i cant seem to pass the address part. Any ideas?
{"fname": "Nick", "mname": "F.", "lname": "Delos Reyes", "birthday": "1995-04-01", "address": { "Country": "America", "state": "New York" }}
Expected output:
Name : Nick F. Delos Reyes
Birthday : 1995-04-01
Address :Caramoran, New York
There are many ways to it. Following is an example to parse the name.
$array = json_decode('{"fname": "Nick", "mname": "F.", "lname": "Delos Reyes", "birthday": "1995-04-01", "address": { "Country": "America", "state": "New York" }}', true);
$name = [$array['fname'], $array['mname'], $array['lname']];
$outputName = 'Name:' . implode(' ', $name);
It uses json_decode() to convert the JSON to an associative array. It then put the name parts in an array. It uses implode() to join the name parts into a string.

Iterating through this JSON string in PHP

This is my file, titled parks.JSON:
{
"state": [
{
"name": "Alabama",
"park1": "Bladon Springs State Park",
"park1Link": "http://www.stateparks.com/bladon_springs_state_park_in_alabama.html",
"park2": "Florala State Park",
"park2Link": "http://www.stateparks.com/florala_state_park_in_alabama.html"
},
{
"name": "Alaska",
"park1": "Chugach State Park",
"park1Link": "http://www.stateparks.com/chugach_state_park_in_alaska.html",
"park2": "Kachemak Bay State Park",
"park2Link": "http://www.stateparks.com/kachemak_bay_state_park_in_alaska.html"
}
]
}
And this is my php embedded in an html file to call it:
$json_url = "../data/parks.JSON";
$parksJSON = file_get_contents($json_url);
$parksData = json_decode($parksJSON, TRUE);
I am not sure how to go about iterating through my array. I, of course, will have all 50 states entered here in theory.
I have read other posts asking this and their methods don't work because my JSON format is always different from theirs it seems!
I would have thought a pretty simple loop would do it
foreach ($parksData["state"] as $state)
{
echo $state["name"];
}

Categories