I'm making a anime search using PHP and the myanimelist API. The issue I am having is, every once and awhile I'll search for something and it will come up with a bunch of XML errors. Which is fine but it won't display the information here is the code.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$search = $_GET['q'];
$username = '';
$password = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://myanimelist.net/api/anime/search.xml?q=$search");
curl_setopt($ch, CURLOPT_USERPWD,$username . ":" . $password);
curl_setopt($ch, CURLOPT_HEADER, 'Magic Browser');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
$data = curl_exec($ch);
$xml = simplexml_load_string($data);
$image = $xml->entry[0]->image;
$title = $xml->entry[0]->title;
$status = $xml->entry[0]->status;
$synopsis = $xml->entry[0]->synopsis;
echo "$image <br><br><b>Title</b>: $title <br> <b>Status</b>: $status <br><b>Synopsis</b>: $synopsis";
?>
EDIT FIXED
<?php
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('display_errors', 1);
$search = $_GET['q'];
$username = '';
$password = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://myanimelist.net/api/anime/search.xml?q=$search");
curl_setopt($ch, CURLOPT_USERPWD,$username . ":" . $password);
curl_setopt($ch, CURLOPT_HEADER, 'Magic Browser');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
$data = curl_exec($ch);
//changed the encoding I don't know if it helped
$data = str_replace('utf-8', 'iso-8859-1', $data);
//replaced — so now it works
$data = str_replace('—', ' ', $data);
$xml = simplexml_load_string($data);
$image = $xml->entry[0]->image;
$title = $xml->entry[0]->title;
$status = $xml->entry[0]->status;
$synopsis = $xml->entry[0]->synopsis;
echo "$image <br><br><b>Title</b>: $title <br> <b>Status</b>: $status <br><b>Synopsis</b>: $synopsis";
?>
The example of what I mean is located here. http://vs3.yuribot.com/mal.php?q=naruto
it took awhile but now its fixed i commented the places that help fix it. Thank you everyone for your help.
You should check if simplexml_load_string returned false if the call failed (remote server not available) and if there is some sort of error message in the XML. If there are, you should skip the info and display the error instead. I can't tell you how they are hidden in the XML, but there is most likely a tag or something similar.
Edit: Just saw in the PHP docs that simplexml_load_string requires a well formed XML string. Maybe you should check if you really got a well-formed XML. Best is you look at the docs and change the code in the way you need.
If you are concerned with the PHP "Notice" or "Warning" messages that sometimes seem to appear on your example, then you can prefix the relevant function call (in this case, "simplexml_load_string") with the "#" symbol to suppress any such messages.
For example:
$xml = #simplexml_load_string($data);
For more information, see PHP's manual for error control.
Related
I'm recently started developing on moodle and one big problem is that whenever i build a plugin with a web page, it don't execute any of my curl commands, i hear that moodle has his own php library(an php file called filelib.php i suppose) with curl commands and i should be using its commands instead of mine, but i don't have much experience with moodle development and php so all that code make me very confused.
i tried this question before and a gentleman helped me with an example, i tried his code and it didn't work(it changed the output but still show an error message, i also tried changing the code to no avail) and i didn't get much of an explanation about how curl commands work on moodle(i'm still grateful for his help) or whats commands on filelib.php will substitue my code, can someone help me?
my code:
<?php
require_once(__DIR__.'/../../config.php');
require_once($CFG->libdir.'/filelib.php');
$PAGE->set_url(new moodle_url(url:'/local/iesde/selecionaraulas.php'));
$PAGE->set_context(\context_system::instance());
$PAGE->set_title('selecionar aulas');
$PAGE->requires->js_call_amd('local_iesde/tabelas', 'init');
echo $OUTPUT->header();
echo $OUTPUT->render_from_template('local_iesde/manageaulas', $templatecontext);
$api_server = 'url';
$api_http_user = 'user';
$api_http_pass = 'pass';
$key_acess = 'key';
$key_name = 'API-KEY';
$format = 'json';
$params = array(
'IDstudent' => 000000,
'IDcourse' => 000000,
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "{$api_server}/format/{$format}");
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curl, CURLOPT_USERPWD, "{$api_http_user}:{$api_http_pass}");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("{$key_name}:{$key_acess}"));
curl_setopt($curl, CURLOPT_NOBODY, 1);
curl_exec($curl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($curl);
var_dump(json_decode($output));
echo $output;
echo $OUTPUT->footer()
the purpose of this curl request is to print a list of ids that will be used on another curl request to generate a video file that will be executed on a videoplayer, the variables:
$api_server = 'url';
$api_http_user = 'user';
$api_http_pass = 'pass';
$key_acess = 'key';
$key_name = 'API-KEY';
$format = 'json';
$params = array(
'IDstudent' => 000000,
'IDcourse' => 000000,
);
Are all needed to execute the commands (one of the reasons i think the gentleman's example didn't work is that it didn't used all the variables of the code to get full validation).
well that is all, i'm very new to all of this so any explanation will help, thanks for the help.
I'm tyring to use curl to print a return from a url. The code I have so far looks like this:
<?php
$street = $_GET['street'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
$url = 'http://eligibility.cert.sc.egov.usda.gov/eligibility/eligibilityservice';
$query = 'eligibilityType=Property&requestString=<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$url_final = $url.''.$url_query;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec ($ch);
curl_close ($ch);
echo $return;
?>
the only obvious problem I know of it that the server being queried uses GET instead of POST. Are there GET alternatives to this method?
curl_setopt($ch, CURLOPT_POST, 0);
Curl uses GET by default. You were setting it to POST. You can override it if you ever need to with curl_setopt($ch, CURLOPT_HTTPGET, 1);
Use file_get_contents() function
file_get_contents
Or curl_setopt($ch, CURLOPT_HTTPGET, 1);
use
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://yourlink.com",
CURLOPT_USERAGENT => 'Codular Sample cURL Request'));
All these years and nobody's given the right answer; the way to build a query string is to use http_build_query() with an array. This automatically escapes everything and returns a simple string.
$xml = '<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$data = [
"eligibilityType" => "Property",
"requestString" => $xml
];
$query = http_build_query($data);
$url .= "?$query";
You are missing a question mark in the URL.
Should be like:
$query = '?eligibilityType=Property&...';
Also, that XML in your URL needs encoding, e.g. use the urlencode() function in PHP.
How can I remove firebase specific data? I use the
php Kreait\Firebase library.
$fg = $database->getReference('raw_check_out')->orderByChild('reciptno')->equalTo($recipt)->getSnapshot();
$reb = $fg->getValue();
$fg->remove();
but this is not working.
Based on your code example:
$fg = $database
->getReference('raw_check_out')
->orderByChild('reciptno')
->equalTo($recipt)
->getSnapshot();
Here $fg does not hold the reference, but the snapshot.
If you want to remove the reference after you have retrieved the data you need, you need the reference itself:
$fg = $database->getReference('raw_check_out');
$query = $fg->orderByChild('reciptno')->equalTo($recipt);
$reb = $query->getSnapshot()->getValue();
$fg->remove();
This function is for unsubscribing users if you want to remove "user-id-8776" and your structure is like:
public function unsubscribe($uid)
{
$ref = $this->database->getReference()->getChild('users')->getChild($uid)->orderByChild($uid)->getReference();
$path = $ref->getUri()->getPath();
$ref->remove();
}
For any other data is more or less the same, you just have to find the reference of data you want to delete it and then you can remove it.
Check Image
You have another option to resolve this problem. This solution given below:
$url = "https://<projectID>.firebaseio.com/chatList/".<jsonFileName>."json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result = curl_exec($ch);
curl_close($ch);
I'm having a lot of trouble integrating Sagepay InFrame Server with PHP, as there are no integration kits available for the new protocol (v3). I have the old kits for v2.23 but much of the code therein is deprecated.
At the moment the only way i have been successful in retrieving an OK status from the Sagepay Server servers is to have a form with the collection of hidden values required by Sagepay, including the cryptography field, and using the server URL as the form action. This gives me a status of 'OK' and the SecurityKey etc in the browser tab, but its not much use in the browser tab as i need that POST response back on my server, not on theirs.
For this i opted for curl. I hold the return values for curl_exec in a variable called $rawresponse, and dump the response after each attempt, and as it stands $rawresponse is returning as a false boolean:
$curlSession = curl_init();
curl_setopt ($curlSession, CURLOPT_URL, $url);
curl_setopt ($curlSession, CURLOPT_HEADER, 0);
curl_setopt ($curlSession, CURLOPT_POST, 1);
$data['Crypt'] = new CurlFile('filename.png', 'image/png', 'filename.png');
curl_setopt ($curlSession, CURLOPT_POSTFIELDS, $data);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT,30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 0);
$rawresponse = curl_exec($curlSession);
Now as you can see here I am having to force the Crypt value to be of type CurlFile, which is what i think is breaking the request, however if i dont do that i get the following error:
"The usage of the #filename API for file uploading is deprecated. Please use the CURLFile class instead"
I can only ascertain from this that the cryptography is being mistaken for a file (possibly because the string starts with #), and to counter this im trying to force it to be an image.
So my question is this - is there a particular way to use CurlFile so cryptography strings can be understood? Is there a better way of integrating this functionality with Sagepay that anyone knows about? It really is a very confusing system, and the good documentation is let down by a complete lack of example.
Apologies for this, I was building the string the wrong way. Just in case anyone has a similar problem in the future i'll paste the code that works for me:
public function registerTransaction()
{
$VPSProtocol = urlencode($_POST['VPSProtocol']);
$TxType = urlencode($_POST['TxType']);
$Vendor = urlencode($_POST['Vendor']);
$VendorTxCode = urlencode($_POST['VendorTxCode']);
$Currency = urlencode($_POST['Currency']);
$Amount = urlencode($_POST['Amount']);
$NotificationURL = urlencode($_POST['NotificationURL']);
$Description = urlencode($_POST['Description']);
$BillingSurname = urlencode($_POST['BillingSurname']);
$BillingFirstnames = urlencode($_POST['BillingFirstnames']);
$BillingAddress1 = urlencode($_POST['BillingAddress1']);
$BillingCity = urlencode($_POST['BillingCity']);
$BillingPostCode = urlencode($_POST['BillingPostCode']);
$BillingCountry = urlencode($_POST['BillingCountry']);
$DeliverySurname = urlencode($_POST['DeliverySurname']);
$DeliveryFirstnames = urlencode($_POST['DeliveryFirstnames']);
$DeliveryAddress1 = urlencode($_POST['DeliveryAddress1']);
$DeliveryCity = urlencode($_POST['DeliveryCity']);
$DeliveryPostCode = urlencode($_POST['DeliveryPostCode']);
$DeliveryCountry = urlencode($_POST['DeliveryCountry']);
$url = "?VPSProtocol=" . $VPSProtocol;
$url .= "&TxType=" . $TxType;
$url .= "&Vendor=" . $Vendor;
$url .= "&VendorTxCode=" . $VendorTxCode;
$url .= "&Currency=" . $Currency;
$url .= "&Amount=" . $Amount;
$url .= "&NotificationURL=" . $NotificationURL;
$url .= "&Description=" . $Description;
$url .= "&BillingSurname=" . $BillingSurname;
$url .= "&BillingFirstnames=" . $BillingFirstnames;
$url .= "&BillingAddress1=" . $BillingAddress1;
$url .= "&BillingCity=" . $BillingCity;
$url .= "&BillingPostCode=" . $BillingPostCode;
$url .= "&BillingCountry=" . $BillingCountry;
$url .= "&DeliverySurname=" . $DeliverySurname;
$url .= "&DeliveryFirstnames=" . $DeliveryFirstnames;
$url .= "&DeliveryAddress1=" . $DeliveryAddress1;
$url .= "&DeliveryCity=" . $DeliveryCity;
$url .= "&DeliveryPostCode=" . $DeliveryPostCode;
$url .= "&DeliveryCountry=" . $DeliveryCountry;
$strPurchaseURL = "https://test.sagepay.com/gateway/service/vspserver-register.vsp";
$arrResponse = $this->requestPost($strPurchaseURL, $url);
dd($arrResponse);
}
public function requestPost($url, $data){
// Set a one-minute timeout for this script
set_time_limit(60);
// Initialise output variable
$output = array();
// Open the cURL session
$curlSession = curl_init();
curl_setopt ($curlSession, CURLOPT_URL, $url);
curl_setopt ($curlSession, CURLOPT_HEADER, 0);
curl_setopt ($curlSession, CURLOPT_POST, 1);
curl_setopt ($curlSession, CURLOPT_POSTFIELDS, $data);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT,30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 2);
$rawresponse = curl_exec($curlSession);
dd($rawresponse);
//Store the raw response for later as it's useful to see for integration and understanding
$_SESSION["rawresponse"]=$rawresponse;
//Split response into name=value pairs
$response = preg_split(chr(10), $rawresponse);
// Check that a connection was made
if (curl_error($curlSession)){
// If it wasn't...
$output['Status'] = "FAIL";
$output['StatusDetail'] = curl_error($curlSession);
}
// Close the cURL session
curl_close ($curlSession);
// Tokenise the response
for ($i=0; $i<count($response); $i++){
// Find position of first "=" character
$splitAt = strpos($response[$i], "=");
// Create an associative (hash) array with key/value pairs ('trim' strips excess whitespace)
$output[trim(substr($response[$i], 0, $splitAt))] = trim(substr($response[$i], ($splitAt+1)));
} // END for ($i=0; $i<count($response); $i++)
// Return the output
return $output;
} // END function requestPost()
I found a script in Web Designer magazine that enables you to gather Album Data from a Facebook Fan Page, and put it on your site.
The script utilizes PHP's file_get_contents() function, which works great on my personal server, but is not allowed on the Network Solutions hosting.
In looking through their documentation, they recommended that you use a cURL session to gather the data. I have never used cURL sessions before, and so this is something of a mystery to me. Any help would be appreciated.
The code I "was" using looked like this:
<?php
$FBid = '239319006081415';
$FBpage = file_get_contents('https://graph.facebook.com/'.$FBid.'/albums');
$photoData = json_decode($FBpage);
$albumID = $photoData->data[0]->id;
$albumURL = "https://graph.facebook.com/".$albumID."/photos";
$rawAlbumData = file_get_contents("https://graph.facebook.com/".$albumID."/photos");
$photoData2 = json_decode($rawAlbumData);
$a = 0;
foreach($photoData2->data as $data) {
$photoArray[$a]["source"] = $data->source;
$photoArray[$a]["width"] = $data->width;
$photoArray[$a]["height"] = $data->height;
$a++;
}
?>
The code that I am attempting to use now looks like this:
<?php
$FBid = '239319006081415';
$FBUrl = "https://graph.facebook.com/".$FBid."/albums";
$ch = curl_init($FBUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$contents = curl_exec($ch);
curl_close($ch);
$photoData = json_decode($contents);
?>
When I try to echo or manipulate the contents of $photoData however, it's clear that it is empty.
Any thoughts?
Try removing curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); I'm not exactly sure what that does but I'm not using it and my code otherwise looks very similar. I'd also use:
json_decode($contents,true); This should put the results in an array instead of an object. I've had better luck with this approach.
Put it in the works for me category.
Try this it could work
$ch = curl_init($FBUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$contents = curl_exec($ch);
$pageData = json_decode($contents);
//object to array
$objtoarr = get_object_vars($pageData);
curl_close($ch);
Use jquery get Json instead This tips is from FB Album downloader GreaseMonkey script