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"];
}
Related
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": [ ... ]
}
I have a problem with fetching the correct data from a decoded JSON file. I don't know if my question is correct since I don't really know what I am doing for the moment.
So, this is what I don't want to do.
$ln = 'https://api.steamprices.net/v2/csgoprices/?id='.market_hash_name.'&key=XXX';
$link1 = file_get_contents($ln);
$myarray1 = json_decode($link1, true);
echo $myarray1['median_price'];
I am trying to get the price for every steam skin that's being loaded in my code. What this code does is that it loads this api link for every item I load. So if I have 50 items, this link will be loaded 50 times, which is not accepted by the API.
What I want to do, is that I want to load it once, and fetch the prices for every item from that exact link. That link would look like this:
https://api.steamprices.net/v2/csgoprices/?&key=XXX
So, lets say I load it once, and then when I want to apply market_hash_name to it, how do I do?
I assume it is something like this.
$priceJson = file_get_contents('https://api.steamprices.net/v2/csgoprices/?key=XXX');
$priceData = json_decode($priceJson, true);
echo $priceData[''.$market_hash_name.'']['price'];
But it doesn't seem to work. I am sorry for this messy explanation, I an unfamiliar with this.
Note that an example response for the api link looks like this:
{
"-r-H1Z1 Shirt": {
"price": 0.11,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3dxC3m4m0ihzss0MKE6NtIt4qs-JukOX73WgETXYze_pxEBA",
"game": "h1z1"
},
"2016 Invitational Crate": {
"price": 0.09,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6APSjJ6BjX9rGBYZ9ioCPzysSX6hNNacA",
"game": "h1z1"
},
"ANGRYPUG Motorcycle Helmet": {
"price": 0.17,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3WySnxyXoUgz870MKd7sFTkZq98oW1ORiqAVsCUYfbNu3SUQqvUSGyY__iEw",
"game": "h1z1"
},
Another output
{
"name":"Aces High Pin",
"price":1210,
"have":2,
"max":9,
"rate":95,
"tr":0
}
Well, the json string you provide isn't valid but something like this may help you
<?php
$jsonData=file_get_contents("json.file"); // simply contains your json string as posted
$jsonArray=json_decode($jsonData,true);
$jsonObject=json_decode($jsonData);
$list_of_MHN=array("2016 Invitational Crate","ANGRYPUG Motorcycle Helmet");
print_r($jsonArray);
exit;
foreach($jsonArray as $hash_name=>$arr){
if(in_array($hash_name,$list_of_MHN)){
print_r($arr);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonArray[$list_of_MHN[$i]])){
print_r($jsonArray[$list_of_MHN[$i]]);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonObject->$list_of_MHN[$i])){
print_r($jsonObject->$list_of_MHN[$i]);
}
}
?>
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.
For example. I want to get coordinates of all node buildings in bbox.
PHP
$queryBuildings="[out:json];node['building']({$y1},{$x1},{$y2},{$x2});out;";
$data = file_get_contents("http://overpass-api.de/api/interpreter?data={$queryBuildings}")
One element from result:
{
"type": "node",
"id": 29537155,
"lat": 54.6744568,
"lon": -2.1421066,
"tags": {
"building": "house",
"description": "Abandoned (2007). Associate with lead mine workings above it?",
"name": "Flushiemere House"
}
}
I want to get only lon and lat fields it's possible?
You can use skeleton print mode (out skel) which omits all tags, thus being slightly shorter. So your request should become: [out:json];node['building']({$y1},{$x1},{$y2},{$x2});out skel;
Currently csv output mode ([out:csv]) is the only mode where you can select the fields to be shown.
<?php
$data = '{
"type": "node",
"id": 29537155,
"lat": 54.6744568,
"lon": -2.1421066,
"tags": {
"building": "house",
"description": "Abandoned (2007). Associate with lead mine workings above it?",
"name": "Flushiemere House"
}
}';
$test = json_decode($data);
var_dump($test->lon);
First use json_decode to parse the response body:
$parsed_data = json_decode($data);
Then you can access the various fields like so:
$lat = $parsed_data->lat;
$lon = $parsed_data->lon;
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.