I wrote this piece of code some time ago but the original project was never finished. But this will probably be useful to somebody so I'm posting it here as a free snippet.
This solves the problem: how do I fetch the list of discussions from Flarum API with just vanilla PHP ?
The Gist below includes a helper class that fetches the discussions from the API, with an optional tag and number of results you can customize via chainable methods, or just by editing the class.
Just change the $flarumUrl
with your own forum base url to get started. To filter by tag, use the "slug" value of that tag (the part that's in the url).
This code is released "as it" under the MIT license, and there are no guarantees. Use at your own risks. Feel free to adapt to your needs or use it as an inspiration to write your own code to query the API.
The Gist also includes an example at how you might want to sanitize and display the results in an HTML page.
Link to Gist
I strongly suggest you cache the results somehow so you're not taking your forum down with too many requests.
Please be careful when echoing the attribute values, as there's a lot of potential XSS vectors. I would also advise to be careful if using contentHtml
without escaping (this should be ok, but depending on your particular setup this could also expose XSS issues). Don't hold me liable for any XSS issue resulting from the use of this snippet. Use a view framework instead of vanilla echos if possible.
End note: if you can use third-party packages, there are many things you can improve. Using Guzzle for example you could specify the user-agent string and add headers to authenticate. This example uses file_get_contents()
because it's the only method easy to use to make a query in vanilla php. I could have used curl, but I'm not bothering with curl without Guzzle, that's just too much hassle.
If you can use Composer in your project, then please forget about this discussion and use https://github.com/flagrow/flarum-api-client instead. It's a more complete and fully tested package that does the same as my vanilla script, but better.