Can not fetch value of an element using Symfony Dom Crawler - php

I am fetching a URL using guzzle POST method . its working and returning the page that I want . but the problem is when I want to get the value of an input element in a form in that page, the crawler returns nothing . I don't know why .
PHP:
<?php
use Symfony\Component\DomCrawler\Crawler;
use Guzzle\Http\Client;
$client = new Client();
$request = $client->get("https://example.com");
$response = $request->send();
$getRequest = $response->getBody();
$cookie = $response->getHeader("Set-Cookie");
$request = $client->post('https://example.com/page_example.php', array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Cookie' => $cookie
), array(
'param1' => 5,
'param2' => 10,
'param3' => 20
));
$response = $request->send();
$pageHTML = $response->getBody();
//fetch orderID
$crawler = new Crawler($pageHTML);
$orderID = $crawler->filter("input[name=orderId]")->attr('value');//there is only one element with this name
echo $orderID; //returns nothing
What should I do ?

You don't have to create a Crawler:
$crawler = $client->post('https://example.com/page_example.php', array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Cookie' => $cookie
), array(
'param1' => 5,
'param2' => 10,
'param3' => 20
));
$orderID = $crawler->filter("input[name=orderId]")->attr('value');
This assumes your POST isn't being redirected, if it is redirected you should add before calling the filter function:
$this->assertTrue($client->getResponse()->isRedirect());
$crawler = $client->followRedirect();

Related

make the variable as string in laravel

how are you ?
I'm using Guzzle to send post method but when i tried to send the post method with variable getting error so i tried to convert it to sting but still same
this is my current code
if $ mobile value is 55454545445 , them the 'numbers' => "{$mobile}" will be different not "55454545445"
$user = Auth::user();
$mobile = $user->mobile;
$client = new Client();
$booking = Booking::where('id', '=', e($id))->first();
if($booking)
{
$booking->booking_status_id = 3;
$booking->save();
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$data = array('userName' => "test",
'apiKey' => "1",
'numbers' => "{$mobile}",
'userSender' => "sender",
'msg' =>'msg',
'msgEncoding' => "UTF8",);
$dataJson = json_encode($data);
$response = $client->post('https://www.test.test',
['body' => $dataJson]
);
i used this
"0{$mobile}"
instead of
"{$mobile}"
and its work

HTTP Guzzle not returning all data

I have created a function that contacts a remote API using Guzzle but I cannot get it to return all of the data available.
I call the function here:
$arr = array(
'skip' => 0,
'take' => 1000,
);
$sims = api_request('sims', $arr);
And here is the function, where I have tried the following in my $response variable
json_decode($x->getBody(), true)
json_decode($x->getBody()->getContents(), true)
But neither has shown any more records. It returns 10 records, and I know there are over 51 available that it should be returning.
use GuzzleHttp\Client;
function api_request($url, $vars = array(), $type = 'GET') {
$username = '***';
$password = '***';
//use GuzzleHttp\Client;
$client = new Client([
'auth' => [$username, $password],
]);
$auth_header = 'Basic '.$username.':'.$password;
$headers = ['Authorization' => $auth_header, 'Content-Type' => 'application/json'];
$json_data = json_encode($vars);
$end_point = 'https://simportal-api.azurewebsites.net/api/v1/';
try {
$x = $client->request($type, $end_point.$url, ['headers' => $headers, 'body' => $json_data]);
$response = array(
'success' => true,
'response' => // SEE ABOVE //
);
} catch (GuzzleHttp\Exception\ClientException $e) {
$response = array(
'success' => false,
'errors' => json_decode($e->getResponse()->getBody(true)),
);
}
return $response;
}
By reading the documentation on https://simportal-api.azurewebsites.net/Help/Api/GET-api-v1-sims_search_skip_take I assume that the server is not accepting your parameters in the body of that GET request and assuming the default of 10, as it is normal in many applications, get requests tend to only use query string parameters.
In that function I'd try to change it in order to send a body in case of a POST/PUT/PATCH request, and a "query" without json_encode in case of a GET/DELETE request. Example from guzzle documentation:
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
Source: https://docs.guzzlephp.org/en/stable/quickstart.html#query-string-parameters

perform an asynchronous query in PHP using "Guzzle"

make an asynchronous query with PHP using Guzzle and not wait for the result.
how to retrieve JSON content into another PHP file?
<?php
require '/tools/guzzle-master/vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$url = 'https://xxxxxxx/receive.php;
/*creating a client*/
$client = new Client();
/*JSON formatting */
$param = array(
'order_id' => 4544,
'type' => 0,
'amount' => 1266,
'fullname' => 'qdxeq',
'account' => 'dqad',
'callback_url' => 'http://yuexingy.top/Withdraw/WithdrawCallback.aspx',
'device_type' => 'dqd',
'device_id' => 'dafwe',
'device_ip' => 'dwe',
);
$json = json_encode($param);//json encoding
$data = array('json'=>$json);
$req = new Request('POST',$url, $data);
//sending the asynchronous request
$promise = $client->sendAsync($req,['timeout' => 10])->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
?>

OpenSubtitles API 401 Unauthorized how to fix?

I'm trying to fetch subtitles from OpenSubtitles (http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC) like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Opensubtitles listing
function data($request){
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml\r\nUser-Agent: PHPRPC/1.0\r\n",
'content' => $request
)));
$server = 'http://api.opensubtitles.org/xml-rpc'; // api url
$file = file_get_contents($server, false, $context);
$response = xmlrpc_decode($file);
return $response;
}
//Get token
$request = xmlrpc_encode_request("LogIn", array('', '', 'eng', 'TemporaryUserAgent'));
$token = data($request)['token'];
//Get listing
$request = xmlrpc_encode_request("SearchSubtitles", array(
'imdb' => '0462499',
'sublanguageid' => 'eng',
'season' => '',
'episode' => '',
'token' => $token
));
$response = data($request);
var_dump($response);
?>
However I keep getting 401 Unauthorized. Does anyone know how to fix this problem? I know it's not a problem with the API because I am able to retrieve the token just fine.
Try using your username/password instead empty string.
And change UserAgent in TemporaryUserAgent in Header as written in
http://trac.opensubtitles.org/projects/opensubtitles/wiki/DevReadFirst
The second request should be in the following format:-
$request = xmlrpc_encode_request("SearchSubtitles", array($token, array(array('sublanguageid' => 'eng', 'imdbid' => 'your_imdbid'))));
Hope this helps.

Get Twitter Following Count

Im creating a widget for a Wordpress site and i am trying to get the twitter following count, I can get the followers count which is taken from http://www.wpbeginner.com/wp-tutorials/displaying-the-total-number-of-twitter-followers-as-text-on-wordpress/. Any help would be great.
thanks Pierce
Current code in functions.php:
// Twitter
function getTwitterFollowers($screenName = 'hellowWorld')
{
// some variables
$consumerKey = 'hidden';
$consumerSecret = 'hidden';
$token = get_option('cfTwitterToken');
// get follower count from cache
$numberOfFollowers = get_transient('cfTwitterFollowers');
// cache version does not exist or expired
if (false === $numberOfFollowers) {
// getting new auth bearer only if we don't have one
if(!$token) {
// preparing credentials
$credentials = $consumerKey . ':' . $consumerSecret;
$toSend = base64_encode($credentials);
// http post arguments
$args = array(
'method' => 'POST',
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => 'Basic ' . $toSend,
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
),
'body' => array( 'grant_type' => 'client_credentials' )
);
add_filter('https_ssl_verify', '__return_false');
$response = wp_remote_post('https://api.twitter.com/oauth2/token', $args);
$keys = json_decode(wp_remote_retrieve_body($response));
if($keys) {
// saving token to wp_options table
update_option('cfTwitterToken', $keys->access_token);
$token = $keys->access_token;
}
}
// we have bearer token wether we obtained it from API or from options
$args = array(
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => "Bearer $token"
)
);
add_filter('https_ssl_verify', '__return_false');
$api_url = "https://api.twitter.com/1.1/users/show.json?screen_name=$screenName";
$response = wp_remote_get($api_url, $args);
if (!is_wp_error($response)) {
$followers = json_decode(wp_remote_retrieve_body($response));
$numberOfFollowers = $followers->followers_count;
} else {
// get old value and break
$numberOfFollowers = get_option('cfNumberOfFollowers');
// uncomment below to debug
//die($response->get_error_message());
}
// cache for an hour
set_transient('cfTwitterFollowers', $numberOfFollowers, 1*60*60);
update_option('cfNumberOfFollowers', $numberOfFollowers);
}
return $numberOfFollowers;
}
It was pretty simple if I just read the documentation anyway...
Instead of followers_count i replaced it with friends_count as outlined in the API 1.1 documentation. :)

Categories