1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Read from JSON/Cached JSON

Discussion in 'XenForo Development Discussions' started by majafy, Aug 7, 2016.

  1. majafy

    majafy Member


    I want use some data from RESTFul API (JSON) and show in sidebar, so I created a template and include in PAGE_CONTAINER,
    and in new template I used <xen:callback> to include and run my php code, in php code I use file_get_contents to read from json.
    everything seems to be ok, but I have 2 questions:

    1- I want to know my way is true or xenForo has some methods for processing JSON APIs?
    2- how can I cache JSON data? because every time the page load, server should connect to JSON url !

  2. Chris D

    Chris D XenForo Developer Staff Member

    XenForo has a HTTP client which you could use. It doesn't really specifically add anything to handle JSON data, but it's obviously a more robust way of downloading data from a HTTP source.

    You could use the XenForo simple cache:
    // Set simple cache data:

    // Get simple cache data:
    $dataFromCache XenForo_Application::getSimpleCacheData('yourUniqueCacheKey');

    // Permanently delete simple cache data:
  3. majafy

    majafy Member

    Thanks Chris,

    Would you please guide me about XenForo HTTP methods too?

  4. Chris D

    Chris D XenForo Developer Staff Member

    Sorry, that would help ;)

    Look at the XenForo_Helper_Http class and how it is used in various places throughout the XF code.
  5. majafy

    majafy Member

    Is there any way to set expire time ?

  6. Chris D

    Chris D XenForo Developer Staff Member

    No, you would have to handle that yourself. The cache is permanent.
  7. majafy

    majafy Member

    Oh, but I need refresh the cache each every 2~3 hours, because my json will update.
    what should I do now ?
  8. Chris D

    Chris D XenForo Developer Staff Member

    You just need to handle refreshing that cache however you want. So maybe storing the last update time, and doing a refresh once that time plus 2-3 hours has past.
  9. Xon

    Xon Well-Known Member

    Keep in mind that data in Simple Cache is loaded on every request. This includes ajax calls, css, deferred task etc.

    You want to keep the contents small, or store it in a custom Data Registry key which you explicitly load when you need it.

Share This Page