api-examples icon indicating copy to clipboard operation
api-examples copied to clipboard

MathPix-API: PHP sample is missing

Open q2apro opened this issue 6 years ago • 3 comments

Could you add an example for PHP, I am stuck with this custom code:

$uploadedFile = file_get_contents('ztest.jpg');

$ch = curl_init();

curl_setopt_array($ch, array(
	CURLOPT_RETURNTRANSFER => true, // receive server response
	CURLOPT_URL => "https://api.mathpix.com/v3/latex",
	CURLOPT_POST => 1,
	CURLOPT_HTTPHEADER => array('Content-Type:application/json'),
	CURLOPT_POSTFIELDS => array(
		"app_id" => "trial",
		"app_key" => "34f1a4cea0eaca8540c95908b4dc84ab",
		"src" => "data:image/jpeg;base64,".base64_encode($uploadedFile), // data	
	)
));

$result = curl_exec($ch);

curl_close($ch);

// further processing
if($result == "OK") 
{
	// **** how to access the latex results?!
	var_dump('Okay');
} 
else 
{
	var_dump($result);
}

I guess the data should not be sent by "src" but differently using CURL.

q2apro avatar Jul 24 '18 13:07 q2apro

I debugged by:

if(!curl_exec($ch)){
	die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}

which gave:

Error: "SSL certificate problem: unable to get local issuer certificate" - Code: 60

Then I uploaded the testing files to my server and got:

string(103) "{"error":"Invalid credentials","error_info":{"id":"http_unauthorized","message":"Invalid credentials"}}"

even though I have an active account and entered valid credentials. Later I saw the info in the dashboard, that we have to wait 2 min.

I waited 2 min, still not working.

q2apro avatar Jul 24 '18 13:07 q2apro

I am not sure if I can send the image data by "src" => "data:image/jpeg;base64,".base64_encode($uploadedFile),.

The trial credentials do not work either!

Can you help me out?

q2apro avatar Jul 24 '18 14:07 q2apro

Got it to run, just have seen now that I need to pass the credentials as HEADERS and not as post data.

This is the working code:

$uploadedFile = file_get_contents('test.jpg');

$data = array(
	"src" => "data:image/jpeg;base64,".base64_encode($uploadedFile), // data
);

$ch = curl_init();

curl_setopt_array($ch, array(
	CURLOPT_URL => "https://api.mathpix.com/v3/latex",
	CURLOPT_RETURNTRANSFER => true, // receive server response
	CURLOPT_POST => 1, // do post
	CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'app_id: trial', 'app_key: 34f1a4cea0eaca8540c95908b4dc84ab'),
	CURLOPT_POSTFIELDS => json_encode($data),		
));

$result = curl_exec($ch);

if(!$result)
{
	die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}

curl_close($ch);

// further processing
var_dump($result);

q2apro avatar Jul 25 '18 08:07 q2apro