How to extract and assign data from cURL output? - php

The code:
function GetCurlPage ($pageSpec)
{
$ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$tmp = curl_exec ($ch);
curl_close ($ch);
$tmp = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $tmp);
return $tmp;
}
$url = "https://www.domain.com/check.php?domain=" .
$domain . "&suffixes=" . $suffixes . "&fuzzysearch=" . $fuzzysearch;
$output = GetCurlPage("$url");
print $output;
It outputs 3 lines of html, however I wanted to assign a variable to each line to then do something with it...
Ie:
if ($line_1_of_output=="Hi")
{
"do something"
}
if ($line_2_of_output=="Hi")
{
"do something else"
}
How can I output each line in it's own variable in XML if this is the best way to go about it?
Thanks!

Unless I am misunderstanding you, you can just explode cURL's output and then loop through the array.
<?php
// cURL code...
$tmp = explode("<br>", $tmp);
foreach ($tmp AS $lnum => $line) {
var_dump($line);
echo '<br>';
}
Try this:
function GetCurlPage ($pageSpec)
{
$ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$tmp = curl_exec ($ch);
curl_close ($ch);
$tmp = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $tmp);
$tmp = explode('<br>', $tmp);
// Test the array.
foreach ($tmp AS $line) {
echo '<pre>';
print_r($line);
echo '</pre>';
}
// Do something with each line.
$tmp[0] = str_replace('foo', 'bar', $tmp[0]);
$tmp[1] = str_replace('animal', 'monkey', $tmp[1]);
$tmp[2] = str_replace('cat', 'dog', $tmp[2]);
return $tmp;
}

Related

Twizo SMS sending using CURL

I have been trying to send SMS using the API instructions from : https://www.twizo.com/developers/documentation/
$data = array(
'sender'=>'Me',
'body'=>'Message',
'recipients'=>'201*****0'
);
$string = http_build_query($data);
$ch = curl_init("https://twizo:API-KEY#api-asia-01.silverstreet.com/v1/sms/submitsimple");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
print_r($server_output);
The code works but returns an error messasge :
{"validation_messages":{"recipients":{"noArraySupplied":"Only array values are allowed for this field"}},"type":"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html","title":"Unprocessable Entity","status":422,"detail":"Failed Validation"}
EDIT2 :
The above problem is fixed but now I want to make this work :
send.php file :
set_time_limit(0);
if(isset($_POST['submit'])){
$letter = $_POST['message'];
$recs = $_POST['rec'];
$mailist = $_POST['number'];
$from = $_POST["from"];
$message = $letter;
$line = 0;
$list = explode("\n",$_POST['number']);
foreach ($list as $number){
$line = $line+1;
}
?>
<H4>Total Number : <?php echo $line; ?> </H4>
<?php
$spamed = 0;
foreach ($list as $number){
$spamed = $spamed+1;
echo " ".$spamed."/".$line." ><b>".$number." => status :";
include "result.php";
}
}
result.php file :
sleep(0.7);
$message_array = array("https://silverstreet:API-KEY#api-asia-01.silverstreet.com/v1/sms/submitsimple");
$mssage = array_rand($message_array);
$url = $message_array[$mssage];
$data = array(
'body' => $message,
'sender' => $from,
'recipients' =>array("$recs")
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$js = json_decode($result);
curl_close($ch);
if($js->message == "ok"){echo "sent";echo "<br>";} else {
if (!isset($js->message)){echo $result;
echo "<br>";
echo $url;
}else {
echo "not sent <br> message =";
echo $js->message;
echo "<br>";
echo $url;}
I think you need a second dimension array for recipients.
$data = array(
'sender'=>'Me',
'body'=>'Message',
'recipients'=>array('201*****0')
);
Try this:
The documentation states the the API key needs to be sent via HTTP headers, the error codes also indicate the same:
$string = http_build_query($data);
$ch = curl_init("https://api-asia-01.silverstreet.com/v1/sms/submitsimple");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'twizo: API-KEY'
));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
print_r($server_output);

removing a "," from the last element in a foreach loop?

i am trying (like hell..) to remove ',' from the last element in a foreach loop.
tried several counter methods, but not really successfully.
[<?php
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/XXXXXXX/media/recent/?access_token=XXXXXXX&count=10");
$result = json_decode($result);
foreach ($result->data as $post) {
echo '{"name":"Hello","imgpath":" ';echo $post->images->low_resolution->url;echo '"},';
}
?>]
Use json_encode()
<?php
...
$json = array();
foreach ($result->data as $post){
$json[]=array(
'name'=>'Hello',
'imgpath'=>$post->images->low_resolution->url,
);
}
header('Content-Type: application/json');
exit(json_encode($json));
?>
Store the whole thing in a string instead of echoing it, then you can cut the last character using $string=substr($string,0,-1);
[<?php
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/XXXXXXX/media/recent/?access_token=XXXXXXX&count=10");
$string="";
$result = json_decode($result);
foreach ($result->data as $post) {
$string.='{"name":"Hello","imgpath":"' . $post->images->low_resolution->url . '"},';
}
echo substr($string,0,-1);
?>]
Maybe something like:
// quick and dirty solution
foreach ($result->data as $index => $post) {
$comma = ',';
if ((int) $index === count($result->data) -1) {
$comma = '';
}
$string.='{"name":"Hello","imgpath":" ';echo $post->images->low_resolution->url;echo '"}'.$comma;
}
I would use implode, quite cleaner:
$result = json_decode($result);
$string = '{"name":"Hello","imgpath":"';
$string .= implode( '}, {"name":"Hello","imgpath":"', $result->data );
$string .= '}';
echo $string;

Dealing with curl to get count for tweets containing that url

I was using following code to decode the tinyurl from twitter:
function MyURLDecode($url)
{
$ch = #curl_init($url);
#curl_setopt($ch, CURLOPT_HEADER, TRUE);
#curl_setopt($ch, CURLOPT_NOBODY, TRUE);
#curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$url_resp = #curl_exec($ch);
preg_match('/Location:\s+(.*)\n/i', $url_resp, $i);
if (!isset($i[1]))
{
return $url;
}
return $i[1];
}
$url = MyURLDecode($url);
This using this result to get tweet count value:
function get_twitter_url_count($url) {
$encoded_url = urlencode($url);
$content = #file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $encoded_url);
return $content ? json_decode($content)->count : 0;
}
Above code works fine. But due to some issue I need to change the Url Decoding function which is as below:
function TextAfterTag($input, $tag)
{
$result = '';
$tagPos = strpos($input, $tag);
if (!($tagPos === false))
{
$length = strlen($input);
$substrLength = $length - $tagPos + 1;
$result = substr($input, $tagPos + 1, $substrLength);
}
return trim($result);
}
function expandUrlLongApi($url)
{
$format = 'json';
$api_query = "http://api.longurl.org/v2/expand?" .
"url={$url}&response-code=1&format={$format}";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $api_query );
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
$fileContents = curl_exec($ch);
curl_close($ch);
$s1=str_replace("{"," ","$fileContents");
$s2=str_replace("}"," ","$s1");
$s2=trim($s2);
$s3=array();
$s3=explode(",",$s2);
$s4=TextAfterTag($s3[0],(':'));
$s4=stripslashes($s4);
return $s4;
}
This code gives decoded url correctly, infact with better accuracy then previous one but now result of this does not works with this function:
function get_twitter_url_count($url) {
$encoded_url = urlencode($url);
$content = #file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $encoded_url);
return $content ? json_decode($content)->count : 0;
}
Rather givig correct count value, it always gives 0.
Can someone tell me what is wrong here?
full code:
<?php
function TextAfterTag($input, $tag)
{
$result = '';
$tagPos = strpos($input, $tag);
if (!($tagPos === false))
{
$length = strlen($input);
$substrLength = $length - $tagPos + 1;
$result = substr($input, $tagPos + 1, $substrLength);
}
return trim($result);
}
function expandUrlLongApi($url)
{
$format = 'json';
$api_query = "http://api.longurl.org/v2/expand?" .
"url={$url}&response-code=1&format={$format}";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $api_query );
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
$fileContents = curl_exec($ch);
/* preg_match('/Location:\s+(.*)\n/i', $fileContents, $i);
if (!isset($i[1]))
{
return '';
}
else
$fileContents = $i[1]; */
curl_close($ch);
$s1=str_replace("{"," ","$fileContents");
$s2=str_replace("}"," ","$s1");
$s2=trim($s2);
$s3=array();
$s3=explode(",",$s2);
$s4=TextAfterTag($s3[0],(':'));
$s4=stripslashes($s4);
return $s4;
}
$url = expandUrlLongApi('http://t.co/SFdM0wjtGA');
echo "Url is : $url <br/>";
$url = get_twitter_url_count($url);
?>

foreach arrays?

Script:
include_once 'simple_html_dom.php';
$ckfile = 'cookie.txt';
foreach (range('a', 'z') as $letters) {
echo $letters;
}
foreach (range('1', '100') as $numbers) {
echo $numbers;
}
$ch = curl_init ("http://site/test.php?letter=".$letters."&page=".$numbers."");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec ($ch);
$html = str_get_html(''.$output.'');
foreach($html->find('a') as $element) {
echo $element->href . '<br>';
}
As you can see there is three arrays seperated, one by one works, but how them 'put together' in one foreach and do 'job' ?
Etc. I'm not familiar with foreach after all, and if i remember correctly, it's my second time with 'them'...
foreach (array_merge($arr1, $arr2, $arr3) as element) { /* do something */ }
array_merge()
include_once 'simple_html_dom.php';
$ckfile = 'cookie.txt';
foreach (range('a', 'z') as $letters) {
echo $letters;
foreach (range('1', '100') as $numbers) {
echo $numbers;
$ch = curl_init ("http://site/test.php?letter=".$letters."&page=".$numbers."");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec ($ch);
$html = str_get_html(''.$output.'');
foreach($html->find('a') as $element) {
echo $element->href . '<br>';
}
}
echo $numbers;
}
But this script will execute for a few minutes... What do you need it for?

Help fixing php/api/curl code please

What I have in place, is a domain availability check, which connects up to an API and outputs "Available: and Unavailable:" from $tmp. Ths below code will only check the availability ONCE.
I would like to check the availability of the domain, multiple times (possibly on a loop?), without having to run restart cURL connection everytime (as it wastes time - 300ms to 1s per query).
I just don't know how I can connect to cURL once and run the loop (doing the check through the API). Help adjusting the code would be very much appreciated! Minimizing the time it takes to output "available/not available" and looping the checks is key.
Thank you.
Current code
<?php
function GetCurlPage ($pageSpec)
{
$ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$tmp = curl_exec ($ch);
curl_close ($ch);
$tmp = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $tmp);
$tmp = explode('<br>', $tmp);
echo $tmp[0];
echo "<br>";
echo $tmp[1];
echo "<br>";
return $tmp;
}
$returnUrl = "http://www.mysite.com.au/check.php";
$url = "https://www.apisite.com.au/availability/check.php?domain=testdomain&suffixes=.com.au";
$output = GetCurlPage("$url");
?>
#Marc B
function getCurlPage($pageSpec) {
if (is_null($ch)) {
$ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
} else {
curl_setopt($ch, CURLOPT_URL, $pageSpec);
}
while ($i < 5) {
$tmp = curl_exec ($ch);
//curl_close ($ch);
$tmp = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $tmp);
$tmp = explode('<br>', $tmp);
echo $tmp[0];
echo "<br>";
echo $tmp[1];
echo "<br>";
echo udate('H:i:s:u');
echo "<br><br>";
$i++;
}
return $tmp;
}
This should answer your question: Persistent/keepalive HTTP with the PHP Curl library?
comment followup:
function getCurlPage($pageSpec) {
if (is_null($ch))
static $ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
} else {
curl_setopt($ch, CURLOPT_URL, $pageSpec);
}
$tmp = curl_exec($ch);
... do NOT close the curl handle, otherwise do the rest the same as before ...
}
Probably won't work as is, doing this off the top of my head and with only 2 hours sleep, but this should be enough to get you started.
And by the way, there's no need to do doublequotes for GetCurlPage("$url"), it's a waste of parser time, as PHP will have to create a new empty string, stuff $url into it, and pass the new string on down. Just do GetCurlPage($url).

Categories