Accessing unnested entries from JSON decoded into a plain array - php

$tempmoviename = "Battleship";
$omdburl = "http://www.omdbapi.com/?t=" . $tempmoviename;
$imdb_json = file_get_contents($omdburl);
$imdb_info = json_decode($imdb_json,true);
print ($imdb_info[0]->runtime[0]);
I can't get it to print the runtime of the movie. I can get it to print the actual website but not the information I need from the website.
In addition to that if I remove true
json_decode($imdb_json,true);
I get this error.
Fatal error: Cannot use object of type stdClass as array
How do I write this so it grabs the data from an array correctly? I also need to swap spaces and dashes in titles like Black Sheep, Black_Sheep to Black%20Sheep?

Do like this... Since you are converting the JSON to array (by passing true in the json_decode()), You need to access it like an array.
<?php
$tempmoviename = "Battleship";
$omdburl = "http://www.omdbapi.com/?t=" . $tempmoviename;
$imdb_json = file_get_contents($omdburl);
$imdb_info = json_decode($imdb_json,true);
echo $imdb_info['Runtime']; //"prints" 131 min

Related

How to extract an object within a JSON object in PHP and assign it the right index

I have the following PHP code (I'll post the important part of it):
// objID
$objects->objID = generateRandomID();
$objects->pointer = array('type'=>'__pointer','objID'=>'dgFg45dG','className'=>'Users');
$jsonStr = file_get_contents($className.'.json'); // This calls a Users.json file stored in my server
$jsonObjs = json_decode($jsonStr, true);
...
$jsonStr = file_get_contents($className.'.json'); // This calls a Users.json file stored in my server
$jsonObjs = json_decode($jsonStr, true);
array_push($jsonObjs, $objects);
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($jsonObjs);
file_put_contents($className.'.json', $jsonData);
// echo JSON data
echo $jsonData;
// ISSUE HERE :(
$jsonStr = file_get_contents($className.'.json');
// Decode the JSON string into a PHP array.
$jsonObjs = json_decode($jsonStr, true);
foreach($jsonObjs as $i=>$obj) {
print_r('<br><br>'.$i.'-- ');
echo
$obj['objID'].', <br>'
.$obj['pointer']["$i"]['objID']. ', '
.$obj['pointer']["$i"]['type']. ', '
.$obj['pointer']["$i"]['className']. '<br><br>'
;
}
// ./ ISSUE
The code above creates a new JSON object into my own Users.json file.
So, when I call this PHP file with a URL string in my browser, just as a test, and I refresh the page a few times, I get the following echo:
0-- VUDjCZX8QX, , ,
1-- 1uWH17OoJP, , ,
[{"objID":"VUDjCZX8QX","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:49","updatedOn":"2018-09-17 05:36:49","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"1uWH17OoJP","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:51","updatedOn":"2018-09-17 05:36:51","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"RkubyQPvqR","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:54","updatedOn":"2018-09-17 05:36:54","number":111,"boolean":true,"array":["john","sarah"]}]
So, what I need to fix is basically the following:
What's the right code to properly get the list of items of the
"pointer" object that's inside each object of my Users.json file?
I try to track the index of my foreach loop, but it doesn't work properly as you can see by the echo posted above when I first execute my PHP code, I get the JSON string of my 1st object, I don't get any print_r(). Then, when I refresh the page a 2nd time, I get the print of the objID string of my 1st object, and again, if I refresh the page a 3rd time, I get the objID of my 2nd object, while there are 3 objects stored in my json file. And so on, in other words, I never get the first object's print info.
What am I doing wrong?
You are passing $i as a string, not as a variable. Use double quotes (") or remove single quotes (') to pass as a variable. This will solve your issue, pointer objects not printing properly.
$obj['pointer'][$i]['objID']
Update
[{"objID":"VUDjCZX8QX","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:49","updatedOn":"2018-09-17 05:36:49","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"1uWH17OoJP","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:51","updatedOn":"2018-09-17 05:36:51","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"RkubyQPvqR","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:54","updatedOn":"2018-09-17 05:36:54","number":111,"boolean":true,"array":["john","sarah"]}]
According to above JSON string, you don't need specify $i.
$obj['pointer']['objID'] should work, since it is associate array.
Thanks to #saumini-navaratnam, I have to use the following foreach:
foreach($jsonObjs as $i=>$obj) {
print_r('<br><br>'.$i.'-- ');
echo
$obj['objID'].', '
.$obj['pointer']['objID']. ', '
.$obj['pointer']['type']. ', '
.$obj['pointer']['className']. '<br><br>'
;
}
In this way, I can properly get the objects of this object:
{"pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"}
In fact, here's the echo I get:
[
{"objID":"pkO8NesS5S","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:03:27","updatedOn":"2018-09-17 07:03:27","number":111,"boolean":true,"array":["john","sarah"]},
{"objID":"rdwJl20krC","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:03:31","updatedOn":"2018-09-17 07:03:31","number":111,"boolean":true,"array":["john","sarah"]},
{"objID":"3WspzmuwMK","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:07:39","updatedOn":"2018-09-17 07:07:39","number":111,"boolean":true,"array":["john","sarah"]}
]
0-- pkO8NesS5S, dgFg45dG, __pointer, Users
1-- rdwJl20krC, dgFg45dG, __pointer, Users
2-- 3WspzmuwMK, dgFg45dG, __pointer, Users

Trying to grab value from html page but getting template back not the value - php

I am making a price crawler for a project but am running into a bit of an issue. I am using the below code to extract values from an html page:
$content = file_get_contents($_POST['url']);
$resultsArray = array();
$sqlresult = array();
$priceElement = explode( '<div>value I want to extract</div>' , $content );
Now when I use this to get certain elements I only get back
Finance: {{value * value2}}
I want to get the actual value that would be displayed on the screen e.g
Finance: 7.96
The other php methods I have tried are:
curl
file_get_html(using simple_html_dom library)
None of these work either :( Any ideas what I can do?
You just set the <div>value I want to extract</div> as a delimiter, which means PHP looks for it to separate your string to array whenever this occurs.
In the following code we use , character as a delimiter:
<?php
$string = "apple,banana,lemon";
$array = explode(',', $string);
echo $array[1];
?>
The output should be this:
banana
In your example you set the value you want to extract as a delimiter. That's why this happens to you. You'll need to set a delimiter between your string you want to obtain and other string you won't need at the moment.
For example:
<?php
$string = "iDontNeedThis-dontExtractNow-value I want to extract-dontNeedEither";
$priceElement = explode('-', $string);
echo "<div>".$priceElement[2]."</div>";
?>
The code should output this to your HTML page:
<div>value I want to extract</div>
And it will appear on your page like this:
value I want to extract
If you don't need to save the whole array in a variable, you can save the one index of it to variable instead:
$priceElement = explode('-', $string)[2];
echo $priceElement;
This will save only value I want to extract so you won't have to deal with arrays later on.

How can I sanitise the explode() function to extract only the marker I require?

I have some php code that extracts a web address. The object I have extracted is of the form:
WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults
Now in PHP I have called this object $linkHREF
I want to extract the id element only and put it into an array (I'm bootstrapping this process to get multiple id's)
So the command is:
$detailPagePathArray = explode("id=",$linkHREF); #Array
Now the problem is the output of this includes what comes after the id tag, so the output looks like:
echo $detailPagePathArray[0] = WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&w
echo $detailPagePathArray[1] = bf&page=1&
echo $detailPagePathArray[2] = 16123012&source=searchresults
Now the problem is obvious, where it'd firstly picking up the "id" in the "wid" marker and cutting it there, however the secondary problem is it's also picking up all the material after the actual "id". I'm just interested in picking up "16123012".
Can you please explain how I can modify my explode command to point it to the particular marker I'm interested in?
Thanks.
Use the built-in functions provided for the purpose.
For example:
<?php
$url = 'http://www.example.com?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults';
$qs = parse_url($url);
parse_str($qs['query'], $vars);
$id = $vars['id'];
echo $id; // 16123012
?>
References:
parse_url()
parse_str()
if you are sure that you are getting &id=123456 only once in your object, then below
$linkHREF = "WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults";
$str = current(explode('&',end(explode('&id', $linkHREF,2))));
echo "id" .$str; //output id = 16123012

array output of number more than 14 chars

i'm using facebook fql to get some data , these data are in array
when i use json to decode the result it gives me users id in that style
$result = json_decode($result, true);
the result from array is 1.0000148607246E+14
instead of 10000148607246
i know its the same number but when i use that result to get new data from facebook "request back" it gives me error with id
the question now is how to convert 1.0000148607246E+14 to 10000148607246 in php
Add the precision setting on to the top of the PHP tag.
<?php
echo $var=1.0000148607246E+14; //"prints" 1.0000148607246E+14
ini_set('precision', 18); // <------------------ Add this on to the top of your code
echo $var=1.0000148607246E+14; //"prints" 1.0000148607246
number_format(1.0000148607246E+14,0,'','');
You can read more here
Output
100001486072460

Parsing JSON string to dictionary swift

I'm trying to access the individual member-fields of a JSON object in PHP from a JSON string but I can't to access the inner-json, all I get is Array.
This is the JSON string
data = (
{
"created_time" = "2018-10-07T04:42:39+0000";
id = 1069496473131329;
name = "NAME_0";
},
{
"created_time" = "2018-09-09T10:31:50+0000";
id = 955684974605664;
name = "NAME_1";
},
At the moment my code is:
$nameString = $_POST["nameData"];
$nameJsonString = json_encode($nameString, JSON_FORCE_OBJECT);
$jsonNameObj = json_decode($nameJsonString, true);
I've been trying to access the individual entry with:
$element = $jsonNameObj['data'][0];
But only receive Array.
Any help would be greatly appreciated,
Cheers :)
After checking the inputted JSON data, I've realised that it doesn't have a consistent form. As opposed to the overall structure being:
JSON -> List -> JSON
Instead, it's:
JSON -> List
The list contains individual elements that can be in a different order. Consequently, calling:
$element = $jsonNameObj['data'][0]['created_time'];
Works sometimes. As there are three-values/object, I can congregate these values into a trio.
I'm sure there's a way to condense this list into a fixed-JSON format but I'm not familiar with how I'd go about that.
At the moment, with a bit of logic on the back-end, I can retrieve the values.
Thanks for your help #Difster and #Osama!

Categories