How to handle efficiently Google Vision API Client Lib response? - php

I'm new to Google Vision API Client Lib
I'm using Vision API Client Lib for PHP to detect text in images, this is my code:
<?php
require 'vendor/autoload.php';
use Google\Cloud\Vision\VisionClient;
function object_to_array($object) {
return (array) $object;
}
$vision = new VisionClient(
['keyFile' => json_decode(file_get_contents("smartcity-credentials.json"), true)]
);
$img = file_get_contents('img2.jpg');
$image=$vision->image($img,['DOCUMENT_TEXT_DETECTION']);
$result=$vision->annotate($image);
$res=object_to_array($result);
var_dump($res);
?>
All I need is using response as an array for handling, but $result returns something likes array of object/object ( sorry because I don't know much of OOP/Object)
Although i convert $result to array $res, but if I use foreach loop
foreach ($res as $key=>$value){
echo $value;
echo '<br>';
}
I get this
Catchable fatal error: Object of class Google\Cloud\Vision\Annotation\Document could not be converted to string
How do we get value (text detected) in above response for using ?.

You should use the methods fullText() and text() in order to access to the detected text, something like this:
$document = $annotation->fullText();
$text = $document->text();
See the specification of these classes Annotation and Document.

you cannot use $value of type Document as string with the echo.
use print_r($annotation); to see what you even get returned.
this document text detection example looks quite alike, notice the nested foreach loops there. also see the documentation:
use Google\Cloud\Vision\VisionClient;
$vision = new VisionClient();
$imageResource = fopen(__DIR__.'/assets/the-constitution.jpg', 'r');
$image = $vision->image($imageResource, ['DOCUMENT_TEXT_DETECTION']);
$annotation = $vision->annotate($image);
$document = $annotation->fullText();
$info = $document->info();
$pages = $document->pages();
$text = $document->text();
here's some more examples; in particular the detect_document_text.php.

Related

Amazon MWS (PHP) - Report Request API functions return without data, no error thrown

I am currently working with the Amazon MWS to integrate some features into wordpress via a plugin. I am using the client libraries provided by amazon found here:
https://developer.amazonservices.com/api.html?group=bde&section=reports&version=latest
Using these client libraries and the sample php files included I have set up my plugin to make two API calls. The first is requestReport
public function requestInventoryReport() {
AWI_Amazon_Config::defineCredentials(); // Defines data for API Call
$serviceUrl = "https://mws.amazonservices.com";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebService_Client(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
$config,
APPLICATION_NAME,
APPLICATION_VERSION);
$request = new MarketplaceWebService_Model_RequestReportRequest();
$request->setMerchant(MERCHANT_ID);
$request->setReportType('_GET_MERCHANT_LISTINGS_DATA_');
self::invokeRequestReport($service, $request);
}
private function invokeRequestReport(MarketplaceWebService_Interface $service, $request) {
try {
$response = $service->requestReport($request);
if ($response->isSetRequestReportResult()) {
// Print Out Data
}
} catch (MarketplaceWebService_Exception $ex) {
// Print Out Error
}
}
and the second is getReportRequestList which has code similar to the first function. I am able to run these functions without any errors. The issue that I am having is that $response->isSetRequestReportResult() returns false. From my understanding and looking into the response object, this would suggest that the response object does not have the result. (Upon printing out the response object I can see that the FieldValue of the result array is NULL.) The call, however, does not throw an error but neither does it have the result.
I did some digging through the code and found that the result does actually get returned from the api call but never gets set to the return object when the library attempts to parse it from XML. I've tracked the error down to this block of code (This code is untouched by me and directly from the amazon mws reports library).
private function fromDOMElement(DOMElement $dom)
{
$xpath = new DOMXPath($dom->ownerDocument);
$xpath->registerNamespace('a', 'http://mws.amazonaws.com/doc/2009-01-01/');
foreach ($this->fields as $fieldName => $field) {
$fieldType = $field['FieldType'];
if (is_array($fieldType)) {
if ($this->isComplexType($fieldType[0])) {
// Handle Data
} else {
// Handle Data
}
} else {
if ($this->isComplexType($fieldType)) {
// Handle Data
} else {
$element = $xpath->query("./a:$fieldName/text()", $dom);
$data = null;
if ($element->length == 1) {
switch($this->fields[$fieldName]['FieldType']) {
case 'DateTime':
$data = new DateTime($element->item(0)->data,
new DateTimeZone('UTC'));
break;
case 'bool':
$value = $element->item(0)->data;
$data = $value === 'true' ? true : false;
break;
default:
$data = $element->item(0)->data;
break;
}
$this->fields[$fieldName]['FieldValue'] = $data;
}
}
}
}
}
The data that should go into the RequestReportResult exists at the beginning of this function as a node in the dom element. The flow of logic takes it into the last else statement inside the foreach. The code runs its query and returns $element however $element->length = 13 in my case which causes it to fail the if statement and never set the data to the object. I have also looked into $element->item(0) to see what was in it and it appears to be a dom object itself matching the original dom object but with a bunch of empty strings.
Now, I'm new to working with the MWS and my gut feeling is that I am missing a parameter somewhere in my api call that is messing up how the data is returned and is causing this weird error, but I'm out of ideas at this point. If anyone has any ideas or could point me in the right direction, I would greatly appreciate it.
Thanks for your time!
** Also as a side note, Amazon Scratchpad does return everything properly using the same parameters that I am using in my code **
These works for me, check if you are missing anything.
For RequestReportRequest i am doing this:
$request = new MarketplaceWebService_Model_RequestReportRequest();
$marketplaceIdArray = array("Id" => array($pos_data['marketplace_id']));
$request->setMarketplaceIdList($marketplaceIdArray);
$request->setMerchant($pos_data['merchant_id']);
$request->setReportType($this->report_type);
For GetReportRequestList i am doing this:
$service = new MarketplaceWebService_Client($pos_data['aws_access_key'], $pos_data['aws_secret_access_key'], $pos_data['config'], $pos_data['application_name'], $pos_data['application_version']);
$report_request = new MarketplaceWebService_Model_GetReportRequestListRequest();
$report_request->setMerchant($pos_data["merchant_id"]);
$report_type_request = new MarketplaceWebService_Model_TypeList();
$report_type_request->setType($this->report_type);
$report_request->setReportTypeList($report_type_request);
$report_request_status = $this->invokeGetReportRequestList($service, $report_request, $report_requestID);

JSON: How to check schema in PHP

I am a newbie. I am trying to make some experience about REST applications in PHP. So I receive (POST) a JSON body and store the value in my database. I just want to make a check if the JSON body I get is in the right way, if it matches the particular schema I set. I need something like this (for example):
my schema:
{"id":"int",
"name":"string",
"value":"double"
}
I just want to check that my JSON body contains the same fields and types. Thanks in advance.
UPDATE
Thanks to all for your answers. I'd like to follow krichprollsch's answer. It's exactly what I need. So I am using Ubuntu 12.04 LTS and NGINX server. I only installed HttpFoundation and Validator components via Composer. Now in my "www" folder I have a folder called "vendor" where Symfony's components are (I don't know if this folder has to be there). In order to check I made a script taken from some examples on the web but I've got a "500 Internal Server Error". The script is this:
<?php
require 'vendor/autoload.php';
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Lenght;
class user{
public function utente(){
$validator = Validation::createValidator();
$violations = $validator->validateValue('Bernhard', new Lenght(array('min'=>10)));
echo $violations;
}
}
$a = new user;
$a->utente();
?>
Any suggestions? Thanks
You can use the Symfony Validator component to validate the data from the json according with your schema : http://symfony.com/doc/master/book/validation.html
<?php
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validation;
//...
$collectionConstraint = new Assert\Collection(
array(
'id' => new Assert\Type(array('type'=>'integer')),
'name' => new Assert\Type(array('type'=>'string')),
'value' => new Assert\Type(array('type'=>'double'))
)
);
//...
$data = json_decode($your_json);
$validator = Validation::createValidator();
$errorList = $validator->validateValue($data, $collectionConstraint);
Using Symfony validator allow you to check complex constraints, not only type of data.
You can also directly validate an hydrated object. Useful if you want to insert into database.
You want chek value???
YOu can decode json strings with json_decode() function.
For example:
$json = {"id":"int",
"name":"string",
"value":"double"
};
$decode = json_decode($json);
if($decode->value == 'Your value') {
//your code
} else {
echo 'Incorerct!';
}
Hey You can decode you json by php
using json_decode function
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$array1 = json_decode($json, true);// it will return an array
for more about json_decode http://in2.php.net/json_decode
and can compare your data structure array ($array2) with this array
by intersecting them.
$result = array_intersect($array1, $array2);
print_r($result);
You can use json_decode to check if it is a valid syntax
$json = '{"id":"int",
"name":"string",
"value":"double"
}';
$decoded = json_decode($json, true);
if($decoded == null){
//your error message
echo "Error in JSON Format";
}
if the string is not valid, json_decode will return a null value

Traversing the XML response from Yandex API using PHP

I am creating a metasearch engine using Yandex API. Yandex gives result in XML format. So we need to traverse the XML response inorder to get the different fields like URL,title ,description etc.
The XML response by Yandex is as follows:
http://pastebin.com/kAVAVri9
This is how i have implemented: paste
$dom5 = new DOMDocument();
if ($dom5->loadXML($site_results)) {
$results = $dom5->getElementsByTagName("response");
$results1 = $results->getElementsByTagName("results");
$results2 = $results1->getElementsByTagName("group");
$totals["yandex"] = 1000;
foreach ($results1 as $link) {
$url = $link->getElementsByTagName("doc")->item(2)->nodeValue;
;
$url = str_replace('http://', '', $url);
if (substr($url, -1, 1) == '/') {
$url = substr($url, 0, strlen($url) - 1);
}
$search_results[$i]["url"] = $url;
$title = $link->getElementsByTagName("doc")->item(4)->nodeValue;
$search_results[$i]["title"] = $title;
$test = $link->getElementsByTagName("doc");
$test1 = $test->getElementsByTagName("title");
$desc = $test1->getElementsByTagName("headline")->item(0)->nodeValue;
$search_results[$i]["desc"] = $desc;
$search_results[$i]["engine"] = 'yandex';
$search_results[$i]["position"] = $i + 1;
$i++;
}
}
I am new to php. Please forgive me if i have done some stupid mistake. I am unable to retrive the results through my implementation. Please help me find the mistake and get the necessary fields from xml response.
Thank you!
The method getElementsByTagName() returns a DOMNodeList:
$results = $dom5->getElementsByTagName("response");
The DOMNodeList does not have a method called getElementsByTagName(), but you call it:
$results1 = $results->getElementsByTagName("results");
Therefore the fatal error is triggered: Whenever in PHP you execute a method on an object that does not exist, you will get a fatal error and your script stops working.
Do not call undefined object methods and you should be fine.
Apart from these basics, for parsing such XML documents I normally suggest SimpleXML, however this XML file is a little specific therfore I suggest to extend from SimpleXML and add the features you likely need to use, in part from regular expressions as well as from DOMDocument.
One concept you should know about when parsing these XML files is Xpath. For example to access the elements you had that many problems with above, you can write the path literally:
/*/response/results/grouping/group
In PHP with SimpleXML this looks like:
$url = 'http://pastebin.com/raw.php?i=kAVAVri9';
$xml = simplexml_load_file($url, 'MySimpleXML');
foreach ($xml->xpath('/*/response/results/grouping/group') as $link) {
# ... operate on $link
}
A larger example:
$url = 'http://pastebin.com/raw.php?i=kAVAVri9';
$url = '../data/yandex.xml';
$xml = simplexml_load_file($url, 'MySimpleXML');
foreach ($xml->xpath('/*/response/results/grouping/group') as $link) {
$url = $link->doc->url->str()->preg('~^https?://(.*?)/*$~u', '$1');
$title = $link->doc->title->text();
$headline = $link->doc->headline->text();
printf("<%s> %s\n%s\n\n", $url, $title, wordwrap($headline));
}
And it's exemplary output:
<www.facebook.com> " Facebook" - a social networking service
Allows users to find and communicate with friends, classmates and
colleagues, share thoughts, photos and videos, and join various groups.
<en.wikipedia.org/wiki/Facebook> Facebook - Wikipedia, the free encyclopedia
Facebook is a social networking service launched in February 2004, owned
and operated by Facebook, Inc. As of September 2012, Facebook has over one
billion active users, more than half of them using Facebook on a mobile
device.
<mashable.com/category/facebook> Facebook
...
The PHP code example above needs some more code to work because it extends from SimpleXML for the ease of use. This is done with the following code:
class MySimpleXML extends SimpleXMLElement
{
public function text()
{
$string = null === $this[0] ? ''
: (dom_import_simplexml($this)->textContent);
return $this->str($string)->normlaizeWS();
}
public function str($string = null)
{
return new MyString($string ?: $this);
}
}
class MyString
{
private $string;
public function __construct($string)
{
$this->string = $string;
}
public function preg($pattern, $replacement)
{
return new self(preg_replace($pattern, $replacement, $this));
}
public function normlaizeWS()
{
return $this->preg('~\s+~', ' ');
}
public function __toString()
{
return (string) $this->string;
}
}
This might be all a little bit much for the beginning, checkout the PHP manual for SimpleXML and the other functions used in the code-example.

Post 1:N (one customer many phonenumbers) JSON Array to android and parse it in PHP

I want to create a more complex JSON Array where a customer (which has a name) has many phonenumbers so that i can parse it in PHP and i need your help.
i.e.:
public Class ContactVO
{
public String diplayname;
public ArrayList<PhoneVO> phonenumbers = new ArrayList<PhoneVO>();
}
public Class PhoneVO
{
public String number;
}
Can s.o. give me an example how to create the above 1:N structure as JSON Array and how to parse it via PHP?
I put everything in a ArrayList and added the GSON library to may project.
The result is:
[
{"contact_id":"1","displayname":"Bjyyyyy","phonenumbers":[{"number":"066-6228"}]},
{"contact_id":"2","displayname":"Rainer Unsinn","phonenumbers":[{"number":"(066) 214-52"}]},
{"contact_id":"3","displayname":"Dieter karpenstein","phonenumbers":[{"number":"06621716669"}]},
{"contact_id":"4","displayname":"Sido","phonenumbers":[{"number":"(085) 011-1555"}]},
{"contact_id":"5","displayname":"Jochen Müller","phonenumbers":[{"number":"01773313261"}]}
]
How should the receiving PHP File lookslike to parse that?
Are you just looking for the json_decode function?
$fromPost = $_POST['contact'];
$object = json_decode($fromPost, true); // Read the doc to decide whether you want the "true" or not
var_dump($object);
Edit:
You could have something like that (not tested)
$string = '[
{"contact_id":"1","displayname":"Bjyyyyy","phonenumbers":[{"number":"066-6228"}]},
{"contact_id":"2","displayname":"Rainer Unsinn","phonenumbers":[{"number":"(066) 214-52"}]},
{"contact_id":"3","displayname":"Dieter karpenstein","phonenumbers":[{"number":"06621716669"}]},
{"contact_id":"4","displayname":"Sido","phonenumbers":[{"number":"(085) 011-1555"}]},
{"contact_id":"5","displayname":"Jochen Müller","phonenumbers":[{"number":"01773313261"}]}
]';
$decoded = json_decode($string);
foreach($decoded as $person) {
echo $person['displayname'] . "\n";
foreach($person['phonenumbers'] as $phone) {
echo $phone['number'] . "\n";
}
}

PHP - JSON to SimpleXML

I have a bunch of PHP web services that construct JSON objects and deliver them using json_encode.
This works fine but I now have a requirement that the web services can also deliver in XML, depending on a given parameter.
I want to stay away from PEAR XML if possible, and hopefully find a simple solution that can be implemented with SimpleXML.
Can anyone give me any advice?
Thanks
You can create an associative array using json_decode($json,true) and try the following function to convert to xml.
function assocArrayToXML($root_element_name,$ar)
{
$xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
$f = function($f,$c,$a) {
foreach($a as $k=>$v) {
if(is_array($v)) {
$ch=$c->addChild($k);
$f($f,$ch,$v);
} else {
$c->addChild($k,$v);
}
}
};
$f($f,$xml,$ar);
return $xml->asXML();
}
// usage
$data = json_decode($json,true);
echo assocArrayToXML("root",$data);

Categories