Parse error: syntax error, unexpected 'curl_setopt' (T_STRING) - php

I wached a youtube video and came across these codes.
my php file index.php
<?php
//initialize session
$ch = curl_init();
//set the URL
$url = "http://localhost:81/data.php"
//set options
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execution
$json=curl_exec($ch);
//close
curl_close($ch);
//decode the json
$json=json_decode($json, true);
//loop through the results
for($i=0;$i<['Metadata']['TotalResults'];$i++){
echo "JSON : <b>First Name = </b>". $json['Result'][$i]["FirstName"]." , <b>Last Name = </b>".$json['Result'][$i]["LastName"];
}
?>
my json file data.php
<?php
//metadata which will contain how many resukts we have
$meta_array['TotalResults'] = 1;
$metadata = '{"Metadata" : ';
$metadata .= json_encode($meta_array). ',';
//the data
$array["FirstName"] = 'Gary';
$array["LastName"] = 'George';
$data[] = $array;
//json encode the array
$json_encoded = utf8_encode(json_encode($data));
echo $metadata . ' "Result" : '.$json_encoded. '}' ;
exit();
?>
I am continuously getting the above mentioned error.
I am new to jason and curl.
please help me to solve my problem.
thanks in advance :)

I can't see any semicolon after the url.
$url = "http://localhost:81/data.php";
^ it is missing
In your code block you are using $i<['Metadata']['TotalResults'] at loop. Here you are missing the variable name that is eventually your array name. An example could be:
$i<$your_array['Metadata']['TotalResults']

Related

How to use json to pass data from a php file to another php file

As mentioned earlier , i am working on the local server as of now in xampp. I have created 2 files index.php and test.php. What i want to achieve is that , index.php will send json data to test.php , with the json data received , the test.php is able to use that json data to turn the statistics into graph.
I am working with the first step , but however , nothing seems to display on my test.php when i tried to do a var_dump($data) , and what i get is NULL. Tried alot of solutions online but none to seems to fix it. I am relatively new to this , so really thanks and appreciate of your help. First php is index.php , second php is test.php.
Do i require a live server as of now in order to see the results in test.php or local server unable to display the result?
<?php
$array = array();
$product = array();
$product[0]['id_product'] = 'A01';
$product[0]['name_product'] = 'Sandal';
$product[0]['price_product'] = '500';
$product[1]['id_product'] = 'A02';
$product[1]['name_product'] = 'Shoes';
$product[1]['price_product'] = '2500';
$array['id'] = '123';
$array['note'] = 'this is my short example';
$array['data'] = $product;
$data = json_encode($array);
$ch = curl_init('http://localhost:8080/practice3/test.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($data));
$result = curl_exec($ch);
var_dump($result);
?>
```````````````````````````````````
<?php
$fp = fopen('php://input', 'r');
$raw = stream_get_contents($fp);
$data = json_decode($raw,true);
echo "hello";
echo $data['id'];
echo $data['note'];
foreach ($data['data'] as $key) {
echo 'id_product : '.$key['id_product'].'<br/>';
echo 'name_product : '.$key['name_product'].'<br/>';
echo 'price_product : '.$key['price_product'].'<br/>';
}
?>
````````````````````````````````````

How to put URL string in json Viber API php

I am a newbie developer trying to learn web development. I am currently working on this project where articles from a website get shared automatically to a viber public chat. I am facing this problem where I cannot put the URL in the media. I think this is because its json. I am not sure what I am doing wrong here. I have included.
<?php
$Tid = "-1";
if (isset($_GET['id'])) {
$Tid = $_GET['id'];
}
$url = 'https://chatapi.viber.com/pa/post';
$jsonData='{
"auth_token":"4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813",
"from": "K9/C2Vz12r+afcwZaexiCg==",
"type":"url",
"media": "$thisID"
// I want to use $thisID as shown above. But when I
do so this error appears [ {"status":3,"status_message":"'media' field value is not a valid url."} ]
// When I use any full form url like https://google.com it works fine
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
?>
This would work as you are using a single quoted literal.
"media": "' . $thisID . '"
But you are always better to make a PHP array or Object and then use json_encode() to create the JSON String like this
$obj = new stdClass;
$obj->auth_token = "4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813";
$obj->from = "K9/C2Vz12r+afcwZaexiCg==";
$obj->type = 'url';
$obj->media = $thisID;
$jsondata = json_encode($obj);
RESULT of echo $jsondata;
{"auth_token":"4750f56f26a7d2ed-f6b44b76f03d039a-9601b6c9d0d46813",
"from":"K9\/C2Vz12r+afcwZaexiCg==",
"type":"url",
"media":"-1"
}

How to remove double quotes from json converted through php queries

I have a string in a json format, but this is giving invalid json format as i am querying it via php loops
{"a":"" works our ‘T’ logo into an intricately perforated pattern. logo — pattern. Height: .36"" (.9 cm) Length: .29"" (.7 cm) " " }
I need the output as
{"a":"works our ‘T’ logo into an intricately perforated pattern. logo †pattern. Height: .36 (.9 cm) Length: .29 (.7 cm)"}
(i think this should be the correct format)
I have tried str_replace ,but it is removing quotes from the start and end as well, and trim() method also removed all the double quotes in the string.
<?php
$a = "" works our ‘T’ logo into an intricately perforated pattern. logo — pattern. Height: .36"" (.9 cm) Length: .29"" (.7 cm) " " ;
echo str_replace('"',"",$a);
?>
and i m getting this error:
Line : 2, Error type : 4
Message : syntax error, unexpected 'works' (T_STRING)
Note: this value is fetched from the DB and i need it to post to some api so that they can get all the values from our api. and i really dnt want to make any changes in our database or our backend from where this value is coming.
Hint or little solution would help i think.
//To highlight more on what i m exactly doing with the json
//see the below code.
<?php
ini_set('max_execution_time', 0);
require __DIR__ . '/app/Mage.php';
umask(0);
Mage::app();
$collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("name");
foreach($collection as $product){
$product_name = strip_tags($product->getName()); //get name of the product
$result = array();
foreach ($products as $product1) {
$label = array_reduce(
$someattrbute,
function ($carry, $item) use ($product1) {
return $carry . $product1->getAttributeText($item) . ' ';
},
''
);
$result[trim($label)] = $product1->getQty();
}
$product_sizeandquantity = json_encode($result); //result
$products_data.= "{";
$products_data.= '"product_name"'.":".'"'.$product_name.'",';
$products_data.= '"product_stock"'.":".'['.$product_sizeandquantity.'],';
$products_data.= "},";
$products_data = rtrim($products_data, ',');
$products_data.= "]";
//echo $products_data;
$url = 'https://www.yourdomain.com/products';
$api_key = 'mykey';
$sec_key = 'secretkey';
$data='scapi_key='.urlencode($api_key).'&scsecret_key='.urlencode($sec_key)."&products=".urlencode($products_data);
//echo $data;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded')
);
$response = curl_exec($ch);
curl_close($ch);
$arr = json_decode($response, true);
echo $arr;
?>
And this is the json i m getting and this is only for one product, but there are many,as it is foreach loop:
[{"product_name":"Flats", "product_stock":[{"38":"1.0000"}]}]
I think that this is valid json, but still want to know what can be done to pass it through the post request of curl in the above code, as error shows that its a json invalid error.
Note: Some of the products also has the height and sizes and content containing double quotes as shown above.

Get location from a stream url in PHP

I'm trying to get the redirect url from a stream using php.
Here's the code I have right now:
<?php
$stream = 'https://api.soundcloud.com/tracks/178525956/stream?client_id=XXXXXX';
$ch = curl_init($stream);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$url = curl_exec($ch);
echo $url;
curl_close($ch);
?>
Which outputs as a string:
{"status":"302 - Found","location":"THE_URL_I_WANT"}
So how ould I go about getting the url I want as a variable?
Thanks
It's simple use json_decode
$data = json_decode($url);
$your_url = $data->location;
How about
$data = json_decode($url);
$location = $data["location"];

Undefined variable error

I am trying to integrate amazon api into my website, so far I have managed to have it navigate to the correct xml part and store that as an variable however i am now trying to insert this varibable into my mysql database and it is giving me this error
Notice: Undefined variable: sql_select in
Fatal error: Call to a member function query() on a non-object
what am i doing wrong?
Entire Code
define('INCLUDED', 1);
error_reporting(E_ALL);
ini_set("display_errors", 1);
$AWS_ACCESS_KEY_ID = "HIDDENFORPRIVACY";
$AWS_SECRET_ACCESS_KEY = "HIDDENFORPRIVACY";
$base_url = "http://free.apisigning.com/onca/xml?";
$url_params = array('Operation'=>"ItemLookup",'Service'=>"AWSECommerceService",
'AWSAccessKeyId'=>$AWS_ACCESS_KEY_ID,'AssociateTag'=>"HIDDENFORPRIVACY",
'Version'=>"2011-08-01",'Availability'=>"Available",'ItemId'=>"0273702440",
'ItemPage'=>"1",'ResponseGroup'=>"EditorialReview", 'Title'=>"Accounting and Finance for Non-Specialists 5th Edition");
// Add the Timestamp
$url_params['Timestamp'] = gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
// Sort the URL parameters
$url_parts = array();
foreach(array_keys($url_params) as $key)
$url_parts[] = $key."=".$url_params[$key];
sort($url_parts);
// Construct the string to sign
//$string_to_sign = "GET\nhttp://free.apisigning.com/".implode("&",$url_parts);
//$string_to_sign = str_replace('+','%20',$string_to_sign);
//$string_to_sign = str_replace(':','%3A',$string_to_sign);
//$string_to_sign = str_replace(';',urlencode(';'),$string_to_sign);
// Sign the request
//$signature = hash_hmac("sha256",$string_to_sign,$AWS_SECRET_ACCESS_KEY,TRUE);
// Base64 encode the signature and make it URL safe
//$signature = base64_encode($signature);
//$signature = str_replace('+','%2B',$signature);
//$signature = str_replace('=','%3D',$signature);
//$signature = str_replace(';',urlencode(';'),$string_to_sign);
$url_string = implode("&",$url_parts);
$url = $base_url.$url_string;
//print $url;
$ch = curl_init(); //this part we set up curl
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$xml_response = curl_exec($ch);
curl_close($ch);
header('Content-type: application/xml'); //specify as xml to not display as one long string
echo $xml_response;
$xml = new SimpleXMLElement($xml_response); //time to echo back the correct piece of data
$editorialReview = $xml->Items->Item->EditorialReviews->EditorialReview->Content;
$variable = '<p>Editorial review: '.html_entity_decode($editorialReview).'</p>'."\n";
echo $variable;
$sql_select = mysql_query("INSERT INTO " . DB_PREFIX . "auctions
(amazon_description) VALUES
('" . $variable . "')");
echo ($sql_select);
this does not send errors, but the mysql database shows no change
The error "Undefined variable" indicates that you have not initialized the object.
From the code you printed it seems that $sql_select should be a string which has the select statement.
So you need to do something like :
$variable = '<p>Editorial review: '.html_entity_decode($editorialReview).'</p>'."\n";
echo $variable;
$sql_select .= "INSERT INTO " . DB_PREFIX . "auctions
(amazon_description) VALUES
('" . $variable . "')";
$DB_object->query($sql_select);
Please post the entire code so that the solution can be accurately found out.

Categories