Is there a simple way to display on my website a specific value, for example "Gonna make this my new alarm ringtone" from following reddit comments .json file: https://www.reddit.com/r/funny/comments/mi0lic/.json
I've found a simple php script that works with reddit user .json files:
... $content = file_get_contents("https://www.reddit.com/user/joshfolgado/about.json");
$result = json_decode($content);
print_r( $result->data->subreddit->title ); ...
But I can't make this work using the comments .json file:
... $content = file_get_contents("https://www.reddit.com/r/funny/comments/mi0lic/.json");
$result = json_decode($content);
print_r( $result->data->children->data->title ); ...
Any other simple script that does the job is also welcome.
The issue can be found here:
print_r( $result->data->children->data->title ); ...
$result->data->children is an Array holding all the comments returned by the API.
We should 'search' all those comments (in your example, it's just 1) for the desired object.
Consider the following code example we're I've used array_filter to custom filter the objects found in $result->data->children array.
<?php
// Search string
$search = 'Gonna make this my new alarm ringtone';
// Get json using CURL
$json = getJson('t3_mi0lic');
// Search ->children
$res = array_filter($json->data->children, function ($child) use ($search) {
// Include if ->data->title qeuals search
return $child->data->title === $search;
});
// Show result
var_dump($res);
// Get JSON by $userId
function getJson($userId) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.reddit.com/api/info/?id=' . $userId,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'
));
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response);
}
I use Request solution for ajax-request, but I get an error:
reqwest.min.js:6 Mixed Content: The page at 'https://...' was loaded
over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://...'. This request has been blocked; the content must be
served over HTTPS.
Server-side code (i'm using wordpress plugin for this):
add_action('wp_ajax_nopriv_wpse144893_search', 'wpse144893_search_data'); // allow logged out users
add_action('wp_ajax_wpse144893_search', 'wpse144893_search_data'); // allow logged in users
function wpse144893_search_data(){
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
$errors = array();
$data = array(
'status' => 'error',
'message' => '',
'result' => array()
);
if(!isset($_REQUEST['term']) || empty($_REQUEST['term']))
$errors[] = 'No search term given!';
if(!isset($_REQUEST['limit']) || empty($_REQUEST['limit']))
$limit = 10;
else
$limit = (int) $_REQUEST['limit'];
if(empty($errors)){
$term = sanitize_text_field($_REQUEST['term']);
// setup query data
$args = array(
'posts_per_page' => $limit,
's' => $term
);
$query = new WP_Query($args); // run query
$results = array();
if($query->have_posts()): while($query->have_posts()): $query->the_post();
$post_item = array(
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'permalink' => get_permalink()
);
$results[] = $post_item;
endwhile;
$data['status'] = 'success';
$data['message'] = 'Results found!';
$data['result'] = $results;
else:
$errors[] = 'No post found!';
$data['message'] = $errors;
endif;
}
echo json_encode($data); // print json
die(); // kill the script
}
Client-side code (request plugin):
reqwest({
url: 'http://...'
, type: 'json'
, method: 'get'
, crossOrigin: true
, withCredentials: true
, error: function (err) { alert('1'); }
, success: function (resp) {
alert('2');
}
})
I tried use this header('Content-type: application/json');header('Access-Control-Allow-Origin: *'); (see in server code above) but it does not solve the problem.
Problem is solved by moving second server to HTTPS...
How to use WordPress REST API to post article? I can edit post using the following PHP code, i'm using the Basic Authentication.
require( dirname(__FILE__) . '/wp-load.php' );
$headers = array (
'Authorization' => 'Basic ' . base64_encode( 'username' . ':' . 'password' ),
);
// Edit post
$url = rest_url( 'wp/v2/posts/1' );
$data = array(
'title' => 'Test API Edit'
);
$response = wp_remote_post( $url, array (
'method' => 'POST',
'headers' => $headers,
'body' => $data
) );
print_r($response);
But I can not post new article
<?php
require( dirname(__FILE__) . '/wp-load.php' );
$headers = array (
'Authorization' => 'Basic ' . base64_encode( 'username' . ':' . 'password' ),
);
// post new article
$url = rest_url( 'wp/v2/create_post/' );
$data = array(
'title' => 'Post from API',
'content' => 'test contents'
);
$response = wp_remote_post( $url, array (
'method' => 'POST',
'headers' => $headers,
'body' => $data
) );
print_r($response);
The return is always No route was found matching the URL and request method
Any suggestions?
It looks like you are using the wrong endpoint for POSTing to the REST API. As mentioned here the endpoint for creating new posts is:
/wp/v2/posts
Hope this solves your problem!
Is it possible to run a web action in a console controller?
In a web controller (yii\web\Controller) I have an action which I would like to run as a cron job. But if I try to run it in a console controller (yii\console\Controller):
Yii::$app->runAction('controller/action');
then I receive the following error message:
Error: Unknown command "controller/action".
Run a web action in a console controller:
Yii::$app->controllerNamespace = "app\controllers";
Yii::$app->runAction('controller/action');
Assign controllerNamespace before running the web action from console.
In addition, disable enableCsrfValidation for the web action:
public function beforeAction($action)
{
if ($action->id == 'action') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
The 'action' ID could be replaced with your current web action ID.
Sorry, I did not understand the context of the question.
As #soju says, you should find a way to do it using CURL, but there is a way.
$config = \yii\helpers\ArrayHelper::merge(
require(Yii::getAlias('#common').'/config/main.php'),
require(Yii::getAlias('#common').'/config/main-local.php'),
require(Yii::getAlias('#frontend').'/config/main.php'),
require(Yii::getAlias('#frontend').'/config/main-local.php')
);
$web_application = new \yii\web\Application($config);
$web_application->runAction('/site/index',['param1' => 1,'param2' => 2]);
You should be aware that the controller works with their behaviors, then the AccessControl could prevent the execution
The solution with cURL.
In the web controller have to be disabled the CSRF validation:
public function beforeAction() {
if ($this->action->id == 'export') {
Yii::$app->controller->enableCsrfValidation = false;
}
return true;
}
The cURL commands in the console Controller can look e.g. like this:
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_REFERER => $url,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEJAR => 'curl-cookie.txt',
CURLOPT_COOKIEFILE => '/var/www/yii/frontend/web/tmp',
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
CURLOPT_USERAGENT => "Dark Secret Ninja/1.0",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => "LoginForm[username]=".$username.
"&LoginForm[password]=".$password.
"&LoginForm[rememberMe]=1",
CURLOPT_SSL_VERIFYPEER => false,
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
if ( $httpCode != 200 ){
echo "Return code is {$httpCode} \n"
.curl_error($ch);
} else {
echo htmlspecialchars($response);
}
curl_close($ch);
I have been assigned to integrate API for my client website. This API is provided by vision6.com.au. There is no much information avialble on their website. Can anyone give me one example which will contact vision6 database and add a contact from our website developed using jquery and php.
Here is the way I am trying
var newVal = {
"id": 1,
"method": "addUser",
"params": [
"APIKEY",
"123456",
{
"username" : "username_123",
"password" : "123456abc",
"first_name" : "First Name",
"last_name" : "Last Name",
"email" : "example#example.com",
"mobile" : "0412312312",
"phone" : "56565656",
"fax" : "57575757",
"position" : "Manager",
"is_read_only" : true,
"timezone" : "Australia/Brisbane",
"email_user" : true,
"is_confirmed" : true
}
]
};
$.ajax({
url: 'http://www.vision6.com.au/api/jsonrpcserver.php?version=3.0',
type: 'POST',
beforeSend: function(){alert('sending');},
data: newVal,
//dataType: 'json',
//data: JSON.stringify(newVal),
//contentType: 'application/json; charset=utf-8',
dataType: 'json',
//async: false,
success: function(msg) { alert(msg);
}
});
This is what I have taken from their documentation
developers.vision6.com.au
For those who wants to integrate using Ruby, I've created a gist with a simple code:
require 'httparty'
url = 'http://www.vision6.com.au/api/jsonrpcserver.php?version=3.0'
api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
JSON.parse(HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({
'method' => 'getSessionInfo', 'params' => [api_key]
})))
JSON.parse(HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({
'method' => 'searchLists', 'params' => [api_key]
})))
list_id = 123456
JSON.parse(HTTParty.post(url, headers: { 'Content-Type' => 'application/json' }, body: JSON.dump({
'method' => 'addContacts', 'params' => [api_key, list_id, [{ 'First Name' => 'Foo', 'Last Name' => 'Bar', 'Email' => 'foo#bar.com' }]]
})))
You will need to download a jsonRPCClient.php and include it in your php file. From my dealings with the Vision6 API, its not very comprehensive and doesn't make much sense until you start getting into it more. Unfortunately, they aren't very helpful in getting you started.
My code to get you started
include 'includes/jsonRPCClient.php';
$list_id = 1234;
$url = "http://www.vision6.com.au/api/jsonrpcserver.php?version=3.0";
$apikey = 'YOURAPIKEYHERE'
$api = new JsonRpcClient($url);
$contact = array();
$contact[] = array(
'First Name' => "John",
'Email' => "sample#email.com"
);
$returnID = $api->addContacts($apikey, $list_id, $contact);
the most important change I found was
$api->addContacts($apikey, $list_id, $contact);
All methods using the API follow this structure
$api ->APIMethod($apikey, $OtherRequiredFields/Arrays);
I suggest to follow their documentation
http://developers.vision6.com.au/3.0/guide/getting-started
Documentation mentions a client library to access their JSON-RPC. Download it, create a free account and generate a working snippet of PHP code from their examples. It also seems to contain a lot of insights and examples. I am just quoting PHP code for addbatch
// setup vars
$list_id01 = 123;
$list_id02 = 456;
$message_id = 111;
$batch_details = array
(array
('list_id' => $list_id01,
'type' => 'list', // all Contacts in List 123
'time' => 'send, // populate Batch time of send
)
array
('list_id' => $list_id02,
'type' => 'contact', // send to contact_list, next
'contact_list' => array(2),array(17),array(18),
'time' => 'send, // populate Batch time of send
));
$queue_id = $api->invokeMethod('addBatch', $message_id, $batch_details,
time() + (24*3600), true);
Once you produce a snippet of code that does an authorization request and a simple action, but DOES NOT behave as you expected you should update your question on SO. I.e. you should post the snippet and the results that you get vs. the results that you expect to get. That might really help to tackle the problem.
I would also recommend to contact support of the service directly.
PS
Unless you will be able to ask a question in form that would be potentially useful to other users, It would be very difficult to get an answer that you seek. Otherwise your question can be qualified as too localized.
<?php
$data = array(www.mtalkz.com)
‘dest’ => ‘0000000000’,
‘msg’=>’This is Test message’,
‘pass’=>’xyz’,
‘send’=>’ALERTS’,
‘uname’=>’ xyz ‘,
‘wapurl’=>’www.mtalkz.com‘
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => “https://mtalkz.com/developer-tools/“,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => “”,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => “POST”,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
“cache-control: no-cache”,
“content-type: multipart/form-data”,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo “cURL Error #:” . $err;
} else {
echo $response;
}
<?php
$data = array(www.mtalkz.com)
‘dest’ => ‘0000000000’,
‘msg’=>’This is Test message’,
‘pass’=>’xyz’,
‘send’=>’ALERTS’,
‘uname’=>’ xyz ‘,
‘wapurl’=>’www.mtalkz.com‘
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => “https://mtalkz.com/developer-tools/“,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => “”,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => “POST”,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
“cache-control: no-cache”,
“content-type: multipart/form-data”,
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo “cURL Error #:” . $err;
} else {
echo $response;
}