Going to this webstie:
http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=AK-47%20%7C%20Redline%20%28Field-Tested%29
Yields this result:
{"success":true,"lowest_price":"5,59€ ","volume":"5,688","median_price":"5,92€ "}
The result is updated every time the page is refreshed. Using PHP, how would I be able to save the result line and split it up in my code I can use it for other things? Would it be viable/possible to do this about 3000-5000 times from a loop in my code, or would it be too much and crash it? I won't be using all the data from it in my code, just saving it into a database and moving to the next result.
That code is JSON and can be parsed with json_decode
$data = file_get_contents('http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=AK-47%20%7C%20Redline%20%28Field-Tested%29');
$json = json_decode($data);
echo $json->volume;
As far as looping... why? You would simply load the page 3000+ times in a row. What would be the benefit of that? Perhaps you should consider a cron job instead, which could fetch the data at regular intervals (and not spam the Steam servers)
Your code is in JSON format.
So:
$content = file_get_contents('http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=AK-47%20%7C%20Redline%20%28Field-Tested%29');
json_decode($content);
Should work correctly
Related
When users keep interacting with my web app, the pages keep doing calls so that some info can be stored in a cookie linked file that is stored on the server (with the PHP session file, it gets complex: I don't have choice to see a complete history, etc.)
So, anyway, with every ajax call, I create json_encoded data in a flat file with the unique cookie name.
Data example of one such cookie file: (keys/values may repeat)
{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}
Now, when I am searching this file, to retrieve data and to do other stuff, I would like to have the entire contents in one big array as if the entire data ws json_encoded in one shot.
How do I do this? I could do a bunch of str_replace and replace the "{" and "}" and get rid of the carriage returns but that seems to be a bit ugly
Is there a better way?
Thanks
I suggest to fix your json format by using str_replace as you saying because this is the only way to have a valid json format on using this function:
$str = '{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}';
$fix_json = "[" . str_replace("}\n{", "},{", $str) . "]";
and after this you can decode you json and convert it with json_decode, like this:
$dataArray = json_decode($fix_json, true);
I'm working on some system for a few hours now and this little thing is too much for me to think logically about at the moment.
Normally I would wait a few hours but this is a last minute job and I need to finish this.
Here's my problem:
I have an XML file that gets posted to my PHP file, the PHP file inserts certain data into a DB, but some XML nodes have the same name:
<accessoires>
<accessoire>value1</accessoire>
<accessoire>value2</accessoire>
<accessoire>value3</accessoire>
</accessoires>
Now I want to get a var $acclist which contains all values seperated by a comma:
value1,value2,value3,
I bet the solution to this is very easy but I'm at the known point where even the easiest piece of code becomes a hassle. And googling only comes up with nodes that in some way have their own identifiers.
Could someone help me out please?
You can try simplexml_load_string to parse the html then call implode on the node after casting to an array.
NOTE This code was tested in php 5.4.6 and behaves as expected.
<?php
$xml = '<accessoires>
<accessoire>value1</accessoire>
<accessoire>value2</accessoire>
<accessoire>value3</accessoire>
</accessoires>';
$dat = simplexml_load_string($xml);
echo implode(",",(array)$dat->accessoire);
For 5.3.x I had to change to
$xml = '<accessoires>
<accessoire>value1</accessoire>
<accessoire>value2</accessoire>
<accessoire>value3</accessoire>
</accessoires>';
$dat = simplexml_load_string($xml);
$dat = (array)$dat;
echo implode(",",$dat["accessoire"]);
You do this by taking a library that is able to parse and process XML, for example with SimpleXML:
implode(',', iterator_to_array($accessoires->accessoire, FALSE));
The key part here is to use iterator_to_array() as SimpleXML offers the same-named child-elements here as an iterator. Otherwise $accessoires->accessoire gives you auto-magically only the first element (if any).
I have been using PHP to call an API and retrieve a set of data in JSON.I need to make 20 batch calls at once. Therefore, speed is very important.
However, I only need the first element, in fact, I only need one data which is right at the beginning of the JSON file, index 0. However, the JSON file returns about 300 sets of data. I have to wait until all the data are ready before I can proceed.
I want to speed up my API calls by eliminating redundant datasets. Is it possible for me to receive the first set of the data only without having to wait until everything is ready and then go indexing the first element?
excuse my english...thank you in advance.
you could use fopen to get the bytes that are guaranteed to have what you need in it and then use regex to parse it. something like:
$max_bytes = 512;
$fp = fopen($url, "r") ;
$data = "" ;
if($fp) {
while(!preg_match('/"totalAmount"\:"(.*)"/U', $data, $match))
$data .= stream_get_contents($fp, $max_bytes) ;
fclose($fp);
if(count($match)){
$totalAmount = $match[1];
}
}
keep in mind that you cant use the string stored in $data as valid json. It will only be partial
no. json is not a "streamable" format. until you receive the whole string, it cannot be decoded into a native structure. if you KNOW what you need, then you could use string operations to retrieve the portion you need, but that's not reliable nor advisable. Similarly, php will not stream out the text as it's encoded.
e.g. consider a case where your data structure is a LOOOONG shallow array
$x = array(
0 => blah
1 => blah
...
999,999,998 => blah
999,999,999 => array( .... even more nested data here ...)
);
a streaming format would dribble this out as
['blah', 'blah' ............
you could assume that there's nothing but those 'blah' at the top level and output a ], to produce a complete json string:
['blah'.... , 'blah']
and send that, but then you continue encoding and reach that sub array... now you've suddenly got
['blah' ....., 'blah'][ ...sub array here ....]
and now it's no longer valid JSON.
So basically, json encoding is done in one (long) shot, and not in dibs and drabs, just because you simply cannot know what's coming "later" without parseing the whole structure first.
No. You need to fetch the whole set before parsing and sending the data you need back to the client machine.
Using PHP, I'm trying to grab data from the Goodreads API, which returns XML. I've been having a hell of a time trying to figure out how to pull data out of it.
At some point in the adventure, someone suggested I do a json decode( json encode ($blah)) of the whole thing and use JSON instead of XML.
That brings me to my current situation. Everything works as it should, up to the point where I'm pulling data out of the returned array. I probably should have spent more time reading and learning about arrays, but after more than two days of doing every Google search I could think of, I came here.
Here's the entirety of what gets returned by Goodreads:
a:2:{s:7:"Request";a:3:{s:14:"authentication";s:4:"true";s:3:"key";a:0:{}s:6:"method";a:0:{}}s:6:"search";a:7:{s:5:"query";a:0:{}s:13:"results-start";s:1:"1";s:11:"results-end";s:1:"1";s:13:"total-results";s:1:"1";s:6:"source";s:9:"Goodreads";s:18:"query-time-seconds";s:4:"0.06";s:7:"results";a:1:{s:4:"work";a:9:{s:11:"books_count";s:1:"7";s:2:"id";s:7:"5024045";s:24:"original_publication_day";s:2:"16";s:26:"original_publication_month";s:1:"9";s:25:"original_publication_year";s:4:"2008";s:13:"ratings_count";s:3:"227";s:18:"text_reviews_count";s:2:"53";s:14:"average_rating";s:4:"4.33";s:9:"best_book";a:5:{s:2:"id";s:7:"4958245";s:5:"title";s:37:"7 Habits of Happy Kids [With Earbuds]";s:6:"author";a:2:{s:2:"id";s:5:"38343";s:4:"name";s:10:"Sean Covey";}s:9:"image_url";s:56:"http://photo.goodreads.com/books/1343744353m/4958245.jpg";s:15:"small_image_url";s:56:"http://photo.goodreads.com/books/1343744353s/4958245.jpg";}}}}}
What I want from this array is the "id" variable appears under "best_book". For that, I'm using these lines of code:
$goodreads_results = json_decode(json_encode((array) simplexml_load_string($goodreads_data_a)), 1);
$goodreads_id = $goodreads_results->search->results->work->best_book->id;
I should point out that the array I posted (that began "a:2:{s:7") is what's contained in $goodreads_results after the above two lines of code. So I know everything UP TO that point works as it should.
For whatever reason, I'm not getting the ID. The $goodreads_id variable is empty.
Can somebody help me figure out why? Even though I know it's likely something basic, I'm lost, and everything is starting to look the same to me.
Try:
<?php
$goodreads_data_a = 'a:2:{s:7:"Request";a:3:{s:14:"authentication";s:4:"true";s:3:"key";a:0:{}s:6:"method";a:0:{}}s:6:"search";a:7:{s:5:"query";a:0:{}s:13:"results-start";s:1:"1";s:11:"results-end";s:1:"1";s:13:"total-results";s:1:"1";s:6:"source";s:9:"Goodreads";s:18:"query-time-seconds";s:4:"0.06";s:7:"results";a:1:{s:4:"work";a:9:{s:11:"books_count";s:1:"7";s:2:"id";s:7:"5024045";s:24:"original_publication_day";s:2:"16";s:26:"original_publication_month";s:1:"9";s:25:"original_publication_year";s:4:"2008";s:13:"ratings_count";s:3:"227";s:18:"text_reviews_count";s:2:"53";s:14:"average_rating";s:4:"4.33";s:9:"best_book";a:5:{s:2:"id";s:7:"4958245";s:5:"title";s:37:"7 Habits of Happy Kids [With Earbuds]";s:6:"author";a:2:{s:2:"id";s:5:"38343";s:4:"name";s:10:"Sean Covey";}s:9:"image_url";s:56:"http://photo.goodreads.com/books/1343744353m/4958245.jpg";s:15:"small_image_url";s:56:"http://photo.goodreads.com/books/1343744353s/4958245.jpg";}}}}}
';
$goodreads_results = unserialize($goodreads_data_a);
echo $goodreads_id = $goodreads_results['search']['results']['work']['best_book']['id'];
?>
Hopefully this will be quite an easy one for you here.
Anyway, I have been having alot of trouble with fread() so have decided to use an api link that I have been able to locate.
The script is simply to convert extracted game server data into a readable format.
The link for the "Serialized" data is : http://api.typefish.co.uk/monitor/sa-mp/80.86.81.14:6969/?info&masterlist&rules&players
Simply put I have very little in the way of ideas on what I can do with this data.
So far this is what I have although I am probably miles off:
$content = file_get_contents("http://api.typefish.co.uk/monitor/sa-mp/80.86.81.14:6969/?info&masterlist&rules&players");
trim($content, "{");
trim($content, "}");
foreach(exlpode(",", $content) as $pieces){
explode(":", $pieces);
}
And now I am stuck. Can someone either tell me a way thats miles better or help me finish off the script with some ideas?
Thanks
This is the code I have now after 2 answers:
$newarray = json_decode($content);
var_dump($newarray);
echo "<br><br>";
echo $newarray->{"mapname"};
The problem is that I am unable to display the variable in this format, how can I rebuild that so I can view the variables.
I have changed this:
echo $newarray->{"mapname"};
to this:
echo $newarray->data->rules->mapname;
This data is in json format. All you need to use to convert it into a php Array is json_decode($content)
Reference: http://us3.php.net/json_decode
And read more about json here: http://www.json.org/
You ar doing it wrong, it's not PHP serialized string, its json output you can use json_decode to get string into PHP array.
Like:
var_dump(json_decode($content, true));