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;
Related
i built a Instagram Story Scraper, but its not working...
I've tried everything, but there's something wrong with my code
I hope you can help me
this is my index.php
<?php
require_once('instagramStory.php');
$story = new instagram_story();
echo $story->getStory("garyvee");
?>
and this is my instagramStory.php
<?php
class instagram_story{
protected function file_get_contents_curl($url){
$cookies = dirname(__FILE__)."/cookie.txt" ;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl, CURLOPT_COOKIEFILE, $cookies);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, true);
$answer = curl_exec($curl);
curl_close($curl);
return $answer;
}
public function getStory($username){
$url = file_get_contents("https://www.instagram.com/$username/");
$json = '/sharedData\s=\s(.*[^\"]);<.script>/ixU';
preg_match_all($json, $url, $jsondata, PREG_SET_ORDER, 0);
$array = json_decode($jsondata[0][1], true);
$user_id = $array['entry_data']['ProfilePage']['0']['graphql']['user']['id'];
$stories = $this->file_get_contents_curl("https://www.instagram.com/graphql/query/?query_hash=de8017ee0a7c9c45ec4260733d81ea31&variables=%7B%22reel_ids%22%3A%5B%22$user_id%22%5D%2C%22tag_names%22%3A%5B%5D%2C%22location_ids%22%3A%5B%5D%2C%22highlight_reel_ids%22%3A%5B%5D%2C%22precomposed_overlay%22%3Afalse%2C%22show_story_viewer_list%22%3Atrue%2C%22story_viewer_fetch_count%22%3A50%2C%22story_viewer_cursor%22%3A%22%22%7D");
$data = json_decode($stories, true);
var_dump($data); die();
$_story = [];
foreach ($stories as $story) {
$vid = 'video_resources';
if (!array_key_exists($vid, $story)) {
$_story [] = $story['display_url'];
} else {
$_story [] = $story['video_resources'][0]['src'];
}
}
foreach ($_story as $story) {
$check = '/mp4/m';
preg_match_all($check, $story, $matches, PREG_SET_ORDER, 0);
if (empty($matches)) {
echo "<a href=$story&dl=1><img src=$story></a>";
} else {
echo '<video width="320" height="240" controls>';
echo '<source src="' . $story . '" type="video/mp4">';
echo '</video>';
echo "<a href=$story&dl=1>Download</a>";
}
}
}
}
?>
this is the error code I get
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);
Here is a simple code I'm trying to run but it does not out put any data. Could someone help? Thanks!!
<?php
$addr = "Hotels in ottawa canada";
$a = urlencode($addr);
$geocodeURL =
"https://maps.googleapis.com/maps/api/geocode/json?address=$a&sensor=false&key=my key";
$ch = curl_multi_init($geocodeURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_multi_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$geocode = json_decode($result);
$lat = $geocode->results[$i]->geometry->location->lat;
$lng = $geocode->results[$i]->geometry->location->lng;
echo $formatted_address = $geocode->results[$i]->formatted_address;
echo $geo_status = $geocode->status;
echo $location_type = $geocode->results[0]->geometry->location_type;
echo $location_type = $geocode->results[$i]->geometry->premise;
echo $street_address = $geocode->results[$i]->street_address;
?>
Social Classifieds
If your looking to pass multiple addresses in parallel to the google api and then parse the results as one, ive put together a little example that does just that and fixed your curl multi code. Hope it helps.
<?php
$urls = array(
'http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true',
'http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode('Hotels').'&sensor=true');
$response = curl_get_multi($urls);
//Handle response array
foreach($response as $json){
$result = json_decode($json);
//echo $result->status.' ';
//Iterate each result
foreach($result->results as $res){
//lat
echo $res->geometry->location->lat.' ';
//lng
echo $res->geometry->location->lng.' ';
//formatted_address
echo $res->formatted_address.' ';
//location_type
echo $res->geometry->location_type.' ';
echo '<br/>';
}
echo '<hr />';
}
/**
* Curl multi function
*
* #param Array $urls
* #return Array
*/
function curl_get_multi($urls) {
$curly = array();
$result = array();
$mh = curl_multi_init();
foreach ($urls as $id=>$url) {
$curly[$id] = curl_init();
curl_setopt($curly[$id], CURLOPT_URL, $url);
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, true);
curl_setopt($curly[$id], CURLOPT_TIMEOUT, 2);
curl_setopt($curly[$id], CURLOPT_USERAGENT, 'CurlRequest');
curl_setopt($curly[$id], CURLOPT_REFERER, $url);
curl_setopt($curly[$id], CURLOPT_AUTOREFERER, true);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $curly[$id]);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while($running > 0);
foreach($curly as $id => $c) {
$result[$id] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
}
curl_multi_close($mh);
return $result;
}
?>
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;
}
This code gives me an empty result. I expect it to print out the titles from the XML-file. I need to use Curl to get the file.
<?php
function get_url($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$xml_content = get_url("http://www.e24.se/?service=rss&type=latest");
$dom = new DOMDocument();
#$dom->loadXML($xml_content);
$xpath = new DomXPath($dom);
$results = $xpath->query('//channel//title/text()');
foreach ($results as $result)
{
echo $result->title . "<br />";
}
?>
I found it already. The loop is wrong. It should be...
foreach ($results as $result)
{
echo $result->nodeValue . "<br />";
}