Pagination and loop through total pages count - php

I am building a small movie database to learn php. I make a call to the API from The Movie DB:
$url = "https://api.themoviedb.org/3/search/movie?api_key=". $apiKey . "&" . $language . "&query=". $searchTerm ."&". $sortBy .""; // path to your JSON file
The results for the search term brother looks like:
object(stdClass)#2 (4) {
["page"]=>
int(1)
["total_results"]=>
int(1202)
["total_pages"]=>
int(61)
["results"]=>
array(20) {
[0]=>
object(stdClass)#3 (14) {
["popularity"]=>
float(18.305)
["vote_count"]=>
int(219)
["video"]=>
bool(false)
["poster_path"]=>
string(32) "/frhzQ5JJ29R3kXuVq3CRYQSczpn.jpg"
["id"]=>
int(327)
["adult"]=>
bool(false)
["backdrop_path"]=>
string(32) "/cL1VX6WllejQQhGTUGGWHW25yor.jpg"
["original_language"]=>
string(2) "en"
["original_title"]=>
string(7) "Brother"
["genre_ids"]=>
array(3) {
[0]=>
int(80)
[1]=>
int(18)
[2]=>
int(53)
}
["title"]=>
string(7) "Brother"
["vote_average"]=>
int(7)
["overview"]=>
string(613) "Ausgestoßen durch die Bruderschaft seines Yakuza-Clans wird der eiskalte Killer Yamamoto gezwungen, Tokio Richtung Los Angeles zu verlassen. Dort angekommen findet er sich selbst sehr schnell in der alten Routine seines gewalttätigen Tokio Leben wieder. In kürzester Zeit formt er eine neue skrupellos operierende Bruderschaft um sich herum. Macht, Mädchen und Geld liegen im zu Füssen. Aber das ist dem ehemaligen Yakuza Killer Yamamoto nicht genug. Er will alles! Er startet einen blutigen und erbitterten Kampf gegen die Mafia und muss wieder einmal feststellen, dass er von seinen Brüdern verraten wird."
The results show that I am one page 1 of 61 with total results of 1202.
I know that I have to loop through the total_pages but I don't know how to build that query around the API call.
I am thankful for every hint.

From their documentation you can see that there is an optional parameter "page". So you can send following requests for each page like:
$url = "https://api.themoviedb.org/3/search/movie?api_key=". $apiKey . "&" . $language . "&query=". $searchTerm ."&". $sortBy . "&page=" . "$pageNumber";

Related

PHP : HTTP_request2: saving a file from reponse body from a post request

I need help making this to work. My request works fine in postman, i get access to my file (zip file in this example) by clicking the button save response as: in postman. In php, i am trying to access the same file but cant find how. Headers are receiving filename, file size etc. I tried to write getBody() to file but its not my file its just a string.
Here is my function to do the post request:
<?php
/**********************************************************************************************/
// Obtention des documents d'un workflow
// reçoit les params:
// MyworkflowId= l'id du workflow
// MyprefixUrl= url de départ de consigno
//
//
// utilise la variable session X-Auth-Token utilisable pour toutes les autres requêtes.
/**********************************************************************************************/
function getDocumentsFromWorkflow($MyprefixUrl,$MyworkflowId)
{
$request = new HTTP_Request2();
$request->setUrl($MyprefixUrl.'/workflows/'.$MyworkflowId.'/documents');
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setConfig(array(
'follow_redirects' => TRUE,
'store_body' => TRUE
));
$request->setHeader(array(
'Content-Type' => 'application/x-www-form-urlencoded'
));
//on passe notre variable session token à l'api pour certifier
//qu'on est authentifié.
$request->addPostParameter(array(
'X-Auth-Token' => $_SESSION['consignoToken']
));
try
{
$response = $request->send();
if ($response->getStatus() == 200)
{
echo "<br> Téléchargement des fichiers du dossier : ". $MyworkflowId;
echo "<br>". $response->getHeader('content-type')."<br>";
echo $response->getHeader('content-disposition')."<br>";
//$myfilename will be treated with substring of Content-Disposition
//for the sake of testing, i wrote a static name identical to the one received in this header
$myfilename = "2020-126.zip";
$filebytes = $response->getHeader('content-length');
//affichage de la taille du fichier en MB avec seulement 2 décimales.
$mysize = number_format($filebytes/1048576,2);
echo $mysize." mb<br>";
echo "<pre>";
$mycontent = $response->getBody();
//var_dump($mycontent);
//fonctionne ouvre le fichier sur le serveur et enregistre.
//
//file_put_contents("uploads/".$myfilename, $mycontent);
/*foreach ($response->getHeader() as $k => $v)
{
echo "\t{$k}: {$v}<br>";
}*/
// tested this to see if file download was triggered but instead of getting my file,
//it saves current php page as filename
//header('Content-Type: '.$response->getHeader('content-type'));
//header('Content-disposition: '.$response->getHeader('content-disposition'));
var_dump($response);
echo "</pre>";
}
else
{
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
}
catch(HTTP_Request2_Exception $e)
{
echo 'Error: ' . $e->getMessage();
}
}
?>
var_dump of response gives:
object(HTTP_Request2_Response)#6 (9) {
["version":protected]=>
string(3) "1.1"
["code":protected]=>
int(200)
["reasonPhrase":protected]=>
string(2) "OK"
["effectiveUrl":protected]=>
string(97) "https://groupetcj.cloud-sandbox1.consigno.com/api/v1/workflows/5f4c3dd954e4f7113c44cfd6/documents"
["headers":protected]=>
array(12) {
["date"]=>
string(29) "Wed, 09 Sep 2020 13:21:49 GMT"
**["content-type"]=>
string(15) "application/zip"**
**["content-length"]=>
string(6) "702727"**
["connection"]=>
string(10) "keep-alive"
["x-auth-token"]=>
string(1900) "H4sIAAAAAAAAAIVWXXeiShD8R/cAxj2HxyUyxLkBnWGm+XgT0IAMxLvGD/z1t4c1EY3uviXDTHVVdXUny46WmZdXs4pO5WlqBhW1/1l2dJOPfH04y0a8zBtl5p2jpKXarJpup40qi+fpD1/I8UwkZrDOT7MJe/LDQ5XG5WG6fj8Goh4H6+Q0E/5TMHk7vj7TsojYY8wWTmlMaYq40zU0Gjs4vR0CwVXgJSNf0Co5paUf+SO883l/lkSmwnrVTNJguU43fOTw3IMqJCBYQ9plrTopDHtaIbdGdfmIn99sdkV03CKvbRIHhmjIRxpibRWUWcOrbPT2Bm7wr36XjPjT4H5ZxPxdeGq3MPl+YcFu8M1AXWWGGtKGbHNLolekTl+oykfBc2bZv6RFrBScLo0S7cUBNZwya6zf4N10k7eBwSx7lzWwLjy1R28uWC1XWUN2hatqrTkd0X0RO6rwgv80zyyCj6SBLrfKTU6cbRKNP/0s0zWz/IgdsFdPgUXWM8GsRPw8Bic2Svqeom4FB8QsU09WsyYts5dAoaZ39IdmbbopPGIsIlvrbZLoeEqx3wuPnMSItlhrs2y+vht5C/rtJsf6WQvb7PlQofdlobErGjF5pLzvI91nHpzwTTZVdC5cWAEERGpO59+FSV9iEwSHaYWYoTCOJDYIC8EGaUCotcva9jnYc1kXKyZ5EMqnKkZ+uQXdIiLbRbxRKdGaYNh71Mo3vc/ocRiNm0znvt1WuVfiGZDlC2a2GZuZd0CP7C61yA6xyv5NjX2Lej0C9ddJYz9NCZ+EvZ/mPmnUVmfqS793xHfpPm9MkkVko3OC93AW/F1qqS6Jac28ostG2IeYrxfVeJ2EPZbKIsxQG7wvYuc1jWtdU2WYh7x1ukUcqG/9d+km846brCkga5Sh8wKGHYZG6gszr/rcR+O2z1Hb+3rIsL8paszkn3Qd96lVoJcF+vbWZ7iwmH7fLDDLhZuWOC/7vDYxl+W+z1/r4MxSG+90aaxzGajUpeNBH/QcfKCOk85P3k1/RB2dS8KpMMYrBg7D/kbn/ksuTSZcIrHffgiB1Np1RqRp/+nbC2KAJN/On0EeX2ODE8ya5Nrv2g65GawkoYTXEHI5nnAIVsJVAp4v35lhz8AlEyDBiruA+ePkTj2XyyMBV2ru51rghsButRDuqnu85syEADmcvzkylPYsNjmJCF/xWiHvHivGd6+8Ps4BuXHkCAYJ+YDvpf+FiI2jA6grfPgdZ1BxqvE5sSdYNx1ww36Ax4ESUeM98xv3oa6hfoe7PEQvER9n2/hYAeJD94jDoCeqwNn+8IRrx4g/wfrOGfNa97kPyH8uwOl/fuwBAc0bCHVCedBYen/geREKE1hsXtdEveh9SrnkuvcsCh/yvupZv88UemiMJZOBHPr11570bzFrJiXsK1/nDBgUhLv9zfs8K9d4kEgXc/BIvxlQbow1ty8+TIEfmpcZucN92M/LjOIeBld5oQRXey+Jup9BF4Fd1Il7nbv2BKRJhGLfvTeIi7nD2TPnUF/X4iadAzii5zfA03tCkPoOVoA45Dzb2rOP29r935E+M4o7zOS6FxQjfMHq//5QMZjdmxo359fZufj5h5ycZ2fo9e2u+nuG7vT0ep/c6DLOfkhO+5xczxnmEc8JD5lU/gDrauYwY693ZvQ6J989ueXX9+CO5s/zId7VfhFGAELC7Dd/3Bk496zfAQ/3B8PdQ+7M38Wbc9YEgI+5HuSFi6GnoTz6oRy/xIbpiJq88Ic7IZ1LVTiy/r6r8T1mB/cKwVCTq9129m2oiTDMe/pg197O8d96cF3rU3Nt93uOGaTfM1Nl2v/sLfy/ala8LhvD/pW3lcu601syD/eF++u1quR4yXbt8646qp//A8Bq1ldVDAAA"
**["content-disposition"]=>
string(35) "attachment; filename="2020-126.zip""**
["x-content-type-options"]=>
string(7) "nosniff"
["x-xss-protection"]=>
string(13) "1; mode=block"
["cache-control"]=>
string(46) "no-cache, no-store, max-age=0, must-revalidate"
["pragma"]=>
string(8) "no-cache"
["expires"]=>
string(1) "0"
["x-frame-options"]=>
string(4) "DENY"
}
["cookies":protected]=>
array(0) {
}
["lastHeader":protected]=>
string(15) "x-frame-options"
["body":protected]=>
string(5792) "PK�J)Qscooter exam.pdf��uT۳��{���g�������Np�$Xpw\���A9���;���޺������u����w��]4����,�4�[�3�(�6���5:??���=����b`g��p��`V%;�����Ϊ��x8y����];��| �M_Pbo�[��:��3��K Nt���߆o���؁�c nп00ǿ����¸������%��q����;���� 0ۿ00����O}#;�?�A`���`���>��`/�8�����������q�������� �'?v�?c�B�_��rs������8؀�������/��/���_vy����8y#\��������/����X����V�gt��R}�Ȫ���
`�z�,V{s;��sq]~1��$H���������K�DAb`NA~6���"*!"�%�������A"< NvInq.A}Veg���4d�xI<Wcg�?��
��FBI�9f�O�KZٺB�Y%m�]!�S3��EnVy����%�%#XU�\��.��c;t�5#���}��bT���
��Ac2�}�q���^�Hd�rbւo�://-H$=('>�6~w����觑�zeϓ�g��;[!�^LZ�5َ���M"m����[85���ʠk�u3#,mxPBNP�&q�9ܦ
4T &�{t��B���J����7������1��Gȕ�\�\e�]!��./��*[#䍽�\Y��!b�nv��
�c��Qt����La�c���#�U�E����������!�{��Rܿ��S�����؋i����������U������K��T����*i��?����
{7c�!j���s���_�yI7[[USg�^bi�n���_^��"��(:� ��ފ9;8�:x겱�d����|9r��Y���x�o3+��WQe����WU .nο���`�\_� ���������!�=egSU��.�˟��ӕU��EXL�UK��b��"#��lfnhke��01�45��X88:�ۙ�Y�Cl!��v�6�?���,���%��?��� �j� f�
����6����\��쇤�va���[�O&�J�5t�㥷��1Pm�>&�͑���$�)��^)Ҙe���ˡ[�421�6ܾ���5��g�����|(��q����� _�9j��%��������.��k���#�z
[��WB�+.�W��Նv�~�Y��N&��2��C��Vd�beQQb2cj�Я���W2�]�|K�Ua��z�Pf�{).+���r{�#zշ�i-�Fׯ��U��2�w3O}w������(0B�8�m9��=#x���ˈ�,M���O�X-�ɝY��-�x9�O�lp��%}2!:�ٛy��s�!�.��,$�?lTlvb��u;Iܶ�я�{Y^,�Ŀ�9��~P �9^��-
�kC��+�����S��z�����~BʾZ{�/�[䯺%������]˜��{SCλs�^^�����סo�J��W�`iƯ�z�7��3r��#��ƿ�{�X��V�b���+�R*giM��wV�5��Ds#��`�Ͱ�al`u�CQz�o/
}�\�
ν���4{��0�x,Gc5����+ȕQ䁂���Jt:���~�ȉ�GPou?��C�I��6�gR��NEH�g!>���;el�4mH��a(s�U��e��+ff�Q���TԎpP����n��}�-
�/�L�'��
����t������^�T����2������2s��l��DV��L�$�� zZDIE�޶�r��c?��O�����|E��_O#'���A�hӁ��lޅ�'I ˁ�c)9v�9&���EhPL�h;��Rc+�գTi����L2�w�d���Mܯ�C��G�xc=c�ߨ��mB�%�<ȗ����2rs�Ε��X�+���j�[�V��+�ޞJ��0G�l��/G~���7j��o�9[�"�A!��s�{A�g��Be��q��?��Q�y|���Ut���d�o*���^u�nl���:YUM�]Uo>���M�;��}��YQJ�O!���U�Y��=[�55�{�����<�<�E���Si���D��S�x�a����vsMO�d=�o^�M��7���)^̱��z��]�l�DW4���LZ�>G����'�P�����b>��Vb`m��:�V���2�����΁W�u���8'jW�m���-n2��t�W�����ccd��͢������(��iO�Z�Eb���ܟ���";�����$�A�c�H��/�A�)�v���A7ηw�k�G� �܉���A��:G��I-���(���.vb�J�;�V2u}��Ϙ��y��ZC��^���]}�vv���=YI��[U�;;�g.P������U'�88�3�܏HI&م�b��~Na��� ,%�o���a�8a��y�Z�a�Y�1!1xT��j.�^�1#�ݳ�Ͼ�Aվ���+cdF����^�A3G~q����#v�C��Q���'ҍ��鳑�+m1���En2����X���R���ZyZ0ޯ-h�$�o2�TM��N{�>�J�,��Z�G�R�L�g�%���h��w�!\�!
5�g�-1n��<\���3�-�#�d!e0R��I��5Y�g��De���$�F��J}3��Ɓˎ�r����UKv��,��7�vhUzH�(|�l���p�U�v��Y��M��t>��
^���F��Ӱ���GU5`����\�%z�F��9v����:�S�i���X>��k��,
�M�c�T�X ��7��<=��x�"?(�襐5�<ő�ү��j��jw�,�
{�j�2���F�����JD�T|李,�#��w�ͫ��2FU+ҌV����ڕ �R{)�j�z�}å�i���+�u�>����ID�?.-�Y�z��5�ī�1�� �lf�����ح^��}#'[\�[�=f�`�.M���W�s�-5h3�:�&�<��t�9"��8��#!YG7�ĸlM�2��x�C�j�X�Ԣu�l�ZTP�k�?l�>�m��5ӏ���|r�:4���R��np��K�P���B��n
��\κ�đI_���aec*�wߞ�<��^Ҁi������<��/��������w�������!E*�L�jvR����*��]X�g�?�L���TN�,����8!`�����Rb;���#�asRuM�(����C��g�v#h��d�*�l�?��;7�#�ib�}b�)q�̲%;$�����(����W��6����k���#?������(���_��0t��Z�qE�,qY-���z�'�)Uז�'؞1���u�=I��6q�����.�C�1w�k�X���Q�Ӹ�0a��)Uz�n�a�8a����t�H]��
��Tu��=m�d�>�1���j�[9m�q����l�j�KgXǫOI?�~M4�|o�} c)�����4�/�"t��ڛ,��##�����BK�H�Z��NKKmS�e�Q�<�OKj�lFZ|������9����~u�������g�sZ���lL���H >K�]�~^�z�]AEThV����g���S�Ó%�c��+�~�h7��G[�����}ƨ����F\���#6,!�����n�:4��Ox3C�k�"zdՊ����q��#m���g��5T� T�4�=ͩ��z�,�Z�Fᎆ'#��fY_O�07��ՉT��N)��732Fx�eL�B��e�v9q9i���wo6�$X)05�Щ��xK��(���+�,��Y��ra�g��:��ZMu�� �my�U�0֞7�{4��6�U��S*X^��:•�k5F���q���w<}}�5]�y��K���s�;�
��>
7��)�
�V蟛�t����uq���5
��,�I/� �+�a<�^��(?�VBPա/��y ��g�GUM�G%F(�D�����e*d���Eh$�"�qT
6��9���Ղ�ue��\M�OY�R2bl��ZͲ)�5ߢU-���o���F��g,��Eђr�.>�Sᣛr�^�ɩ����iq��j1�*��}�����KA��t�uW0~;P�5TN��m�O$jh���2�ҏ�
߸�FG�n#���%�R�&�Ej�����T���4��l󒐤�u�i�.�L{8t�{���D�;3]���Oth�ҧAwҲt�< Y��y~����{x�(�<�/��Ht'a�h�A9 '"e�H7��S9TR�eB�����ϩ=9�ğ��u�
'�K^���&+r��[�����k�\�#XĿ���uن�Ri�*��̵�dp�gj����A�Ƚ���I�XA�j��D#��J�D��g��nM� a�=�R�GM�|� A�W��$˕!���?��Ip�j�uڒ̏�n~�|����p�ɱ=�c�**����]��~nh��|b��鞲}R��+����I��7�_#����ʝZ�x�a�'����SR%|c�/s�͏_ms���d:^ˌK7i�$$5/��*n3�\A� �O��K{
9�%�SN��P�⭥�9��g��ϙ�d&U� �6��z���<��'���܋,/��/|�ψo5�;�P��<�O�m|^���V›-�����&s�÷?\��Q#w��m
gq֛Ɛ�t��]H!���&�
O�])t-fv���hrNFIh���f�W���Ӂ3��������楤f��%���>�t��X�NZ�<��Y*��qx)�&!���=e��+ݡ4�'�9׺TY^KN�B�U�}"�O*�ko,~��#'�P�C���n8ÐBf�v�;�n�/��g�\��Q���Q�Eq�&8�^O�����‹m��`^
��*;�u܏���t�X*��m��7�|��OO���Tr|�sz̮8�i� �
�MT$�G��V�.���?N��K~�,�����|}�Ռ���a}��ZPe�^\D���;~b_�4Q��o��ra��s���s�
���}΄��ƺ��|x�5���v^�Nf��1��sD�"�w-v�dD����4�'
+
����ִ��PV�)No�����_�.v�<f(cduEI�k�(l��]St�
��P���������"�A&�3�O��(�CB��>d{�(.���?t+�zS9g�.=el ,��c�Q'nN}�G��C�ֵU^�!���1=�/��?}.���ޮ3��5c�u�KaV�u����0z�Ƚ�L�Ƈ�-���.�q�b<��S>��A��G9�mϽ�Q0=c�p"�� ي�h�mV�C2�!ף쁧w27���BL����z���~��=�1Z"�"Q�''Y�J�"�Z̢�z%�BB�oO��5р43���H4E,^��^)Ks14 �
�?H�W��h0��p�0�?�H�_�zƘ����Je=�{O��E��4�A,n�~�rݷ�[K2mVR�ms��#]�j����9N("
["bodyEncoded":protected]=>
bool(true)
}

Why is json_decode output always null?

i have an issue where when i do a return $record in my function below i get valid json in postman pretty view but if i try print_r($record) i have a null at the end of the json.
Then when i try to json_decode the out put is always null for some reason.
If anyone has any ideas why this might be happening i am greatful for your input.
Thanks
function webhook_listener($request_data){
$client = new ZohoCRMClient('Contacts', 'API key Here');
$parameters = $request_data->get_params();
if( !isset( $parameters['contactId'] ) || empty($parameters['contactId']) ){
file_put_contents(plugin_dir_path( __FILE__ ).'invalid.txt', 'No parameter found');
return array( 'error' => 'no_parameter_given' );
}else{
$companyid = $parameters['contactId'];
//file_put_contents(plugin_dir_path( __FILE__ ).'crm.txt', $parameters);
$record = $client->getRecordById()->id($companyid)->request();
$record = json_decode($record);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
throw new RuntimeException("JSON decode error: $error");
}
echo $company = $record[1]['data']['Company'];
}
}
JSON:
{"1":{"index":1,"data":{"CONTACTID":"3345923000000546002","SMOWNERID":"3345923000000158021","Contact Owner":"Frank Rosa","First Name":"Administrator","Last Name":"Ian","Email":"poojarajan3ellc#gmail.com","Created Time":"2018-09-19 14:32:35","Modified Time":"2018-09-20 02:48:51","Full Name":"Administrator Ian","Description":"Equity and Empowerment through Education. It is the Mission of 3e LLC to promote equity and empowerment for all students through engaging professional development for educators and parents, one-on-one coaching for teacher efficacy, and mentoring services for youth to promote enrichment and success. For the empowered, we offer editing, transcribing, and ghostwriting services to ensure your voice is heard.","Last Activity Time":"2018-09-20 02:48:51","Instagram Url":"http:\/\/www.instagram.com\/3e_llc","Company":"3ELLC","Website":"https:\/\/www.3ellc.org","Phone_1":"(727) 420-1050","Full Address":"2152 Arcadia Rd, Holiday, FL 34690, USA","Facebook Url":"http:\/\/www.facebook.com\/3eLLC\/","Logo Url":"https:\/\/dev.energypages.com\/wp-content\/uploads\/2018\/05\/header-logo-57.png","Twitter Url":"http:\/\/www.twitter.com\/3e_llc","Membership Level":"Basic","Select Service":"Technology","User ID":"347"}}}
var_dump output:
array(1) {
[1]=>
object(CristianPontes\ZohoCRMClient\Response\Record)#2068 (2) {
["index"]=>
int(1)
["data"]=>
array(22) {
["CONTACTID"]=>
string(19) "3345923000000546002"
["SMOWNERID"]=>
string(19) "3345923000000158021"
["Contact Owner"]=>
string(10) "Frank Rosa"
["First Name"]=>
string(13) "Administrator"
["Last Name"]=>
string(3) "Ian"
["Email"]=>
string(25) "poojarajan3ellc#gmail.com"
["Created Time"]=>
string(19) "2018-09-19 14:32:35"
["Modified Time"]=>
string(19) "2018-09-20 02:48:51"
["Full Name"]=>
string(17) "Administrator Ian"
["Description"]=>
string(407) "Equity and Empowerment through Education. It is the Mission of 3e LLC to promote equity and empowerment for all students through engaging professional development for educators and parents, one-on-one coaching for teacher efficacy, and mentoring services for youth to promote enrichment and success. For the empowered, we offer editing, transcribing, and ghostwriting services to ensure your voice is heard."
["Last Activity Time"]=>
string(19) "2018-09-20 02:48:51"
["Instagram Url"]=>
string(31) "http://www.instagram.com/3e_llc"
["Company"]=>
string(5) "3ELLC"
["Website"]=>
string(21) "https://www.3ellc.org"
["Phone_1"]=>
string(14) "(727) 420-1050"
["Full Address"]=>
string(39) "2152 Arcadia Rd, Holiday, FL 34690, USA"
["Facebook Url"]=>
string(30) "http://www.facebook.com/3eLLC/"
["Logo Url"]=>
string(73) "https://dev.energypages.com/wp-content/uploads/2018/05/header-logo-57.png"
["Twitter Url"]=>
string(29) "http://www.twitter.com/3e_llc"
["Membership Level"]=>
string(5) "Basic"
["Select Service"]=>
string(10) "Technology"
["User ID"]=>
string(3) "347"
}
}
}
null
Output above is the raw view in postman. and in pretty view i got this error (Unexpected 'a')
All the answers here on how to parse jSON were correct. But i was using a php library for my link to zoho which handles the data differently, so i had to do a foreach on my response from the API then json_encode() the data and json_decode() to get the values.
Library i am using: https://github.com/cristianpontes/zoho-crm-client-php
foreach($record as $records){
$payload = $records->getData();
$payload = json_encode($payload);
$payload = json_decode($payload, true);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
throw new RuntimeException("JSON decode error: $error");
}
$company = $payload['Company'];
}
Thanks to everyone that helped especially #miken32

imap_body() returning empty string

Hello fellow developers,
Im currently trying to read all emails with imap. Im trying to get the header infos with imap_headerinfo and the body with imap_fetchbody.
However, I get all the headerinfo but I only get an empty string as a return from the fetchbody function. I hope someone can help me
$this->inbox = imap_open($server, $user, $password);
// Header und Body der Email auslesen
$emails = imap_search($this->inbox,'ALL');
foreach($emails as $k) {
$this->email_contents[$k] = array(
'header' => imap_headerinfo($this->inbox, $k),
'body' => imap_fetchbody($this->inbox, $k, '1')
);
}
imap_close($this->inbox);
fetch_structure
object(stdClass)#65 (11) {
["type"]=>
int(1)
["encoding"]=>
int(0)
["ifsubtype"]=>
int(1)
["subtype"]=>
string(5) "MIXED"
["ifdescription"]=>
int(0)
["ifid"]=>
int(0)
["ifdisposition"]=>
int(0)
["ifdparameters"]=>
int(0)
["ifparameters"]=>
int(1)
["parameters"]=>
array(1) {
[0]=>
object(stdClass)#66 (2) {
["attribute"]=>
string(8) "boundary"
["value"]=>
string(36) "------------CC4C1146391EA6C129642420"
}
}
["parts"]=>
array(2) {
[0]=>
object(stdClass)#67 (12) {
["type"]=>
int(0)
["encoding"]=>
int(1)
["ifsubtype"]=>
int(1)
["subtype"]=>
string(5) "PLAIN"
["ifdescription"]=>
int(0)
["ifid"]=>
int(0)
["lines"]=>
int(30)
["bytes"]=>
int(590)
["ifdisposition"]=>
int(0)
["ifdparameters"]=>
int(0)
["ifparameters"]=>
int(1)
["parameters"]=>
array(2) {
[0]=>
object(stdClass)#68 (2) {
["attribute"]=>
string(7) "charset"
["value"]=>
string(5) "utf-8"
}
[1]=>
object(stdClass)#69 (2) {
["attribute"]=>
string(6) "format"
["value"]=>
string(6) "flowed"
}
}
}
[1]=>
object(stdClass)#70 (13) {
["type"]=>
int(5)
["encoding"]=>
int(3)
["ifsubtype"]=>
int(1)
["subtype"]=>
string(4) "JPEG"
["ifdescription"]=>
int(0)
["ifid"]=>
int(0)
["bytes"]=>
int(1036)
["ifdisposition"]=>
int(1)
["disposition"]=>
string(10) "attachment"
["ifdparameters"]=>
int(1)
["dparameters"]=>
array(1) {
[0]=>
object(stdClass)#71 (2) {
["attribute"]=>
string(8) "filename"
["value"]=>
string(11) "logo_sm.jpg"
}
}
["ifparameters"]=>
int(1)
["parameters"]=>
array(1) {
[0]=>
object(stdClass)#72 (2) {
["attribute"]=>
string(4) "name"
["value"]=>
string(11) "logo_sm.jpg"
}
}
}
}
}
imap-fetchbody() works unusually when handling attached email messages and it's behaviour is inconsistent.
I was going to re-write this but to be honest the author atamido does a fantastic job of showing why this happens so i'll humbly cite his lead comment from this:: http://php.net/manual/en/function.imap-fetchbody.php he also includes an example of how to extract the body
imap-fetchbody() will decode attached email messages inline with the
rest of the email parts, however the way it works when handling
attached email messages is inconsistent with the main email message.
With an email message that only has a text body and does not have any mime attachments, imap-fetchbody() will return the following
for each requested part number:
(empty) - Entire message
0 - Message header
1 - Body text
With an email message that is a multi-part message in MIME format, and contains the message text in plain text and HTML, and has
a file.ext attachment, imap-fetchbody() will return something like the
following for each requested part number:
(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - file.ext
Now if you attach the above email to an email with the message text in plain text and HTML, imap_fetchbody() will use this type of
part number system:
(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - MESSAGE/RFC822 (entire attached message)
2.0 - Attached message header
2.1 - TEXT/PLAIN
2.2 - TEXT/HTML
2.3 - file.ext
Note that the file.ext is on the same level now as the plain text and
HTML, and that there is no way to access the MULTIPART/ALTERNATIVE in
the attached message.
Here is a modified version of some of the code from previous posts
that will build an easily accessible array that includes accessible
attached message parts and the message body if there aren't multipart
mimes. The $structure variable is the output of the
imap_fetchstructure() function. The returned $part_array has the
field 'part_number' which contains the part number to be fed directly
into the imap_fetchbody() function.
<?php
function create_part_array($structure, $prefix="") {
//print_r($structure);
if (sizeof($structure->parts) > 0) { // There some sub parts
foreach ($structure->parts as $count => $part) {
add_part_to_array($part, $prefix.($count+1), $part_array);
}
}else{ // Email does not have a seperate mime attachment for text
$part_array[] = array('part_number' => $prefix.'1', 'part_object' => $obj);
}
return $part_array;
}
// Sub function for create_part_array(). Only called by create_part_array() and itself.
function add_part_to_array($obj, $partno, & $part_array) {
$part_array[] = array('part_number' => $partno, 'part_object' => $obj);
if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type
//print_r($obj);
if (sizeof($obj->parts) > 0) { // Check to see if the email has parts
foreach ($obj->parts as $count => $part) {
// Iterate here again to compensate for the broken way that imap_fetchbody() handles attachments
if (sizeof($part->parts) > 0) {
foreach ($part->parts as $count2 => $part2) {
add_part_to_array($part2, $partno.".".($count2+1), $part_array);
}
}else{ // Attached email does not have a seperate mime attachment for text
$part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
}
}
}else{ // Not sure if this is possible
$part_array[] = array('part_number' => $prefix.'.1', 'part_object' => $obj);
}
}else{ // If there are more sub-parts, expand them out.
if (sizeof($obj->parts) > 0) {
foreach ($obj->parts as $count => $p) {
add_part_to_array($p, $partno.".".($count+1), $part_array);
}
}
}
}
?>

PHP IMAP Get Signed attachment

I have problem with parsing email message with PHP IMAP. Problem is that I have message signed with pkcs#7 signature. Mail contains some text and 2 attachments first one is smime.p7s and second one is message.htm which is html attachment I would like to parse.
To be honest I have no idea how can I access content of this file.
$hostname = '{host}INBOX';
$username = 'name';
$password = 'pass';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'UNSEEN');
$msg = Array();
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
$structure = imap_fetchstructure ( $inbox,$email_number,FT_UID);
echo "<pre>";
var_dump($structure);
echo "</pre>";
break;
}
}
I get full structure and I can find there part:
object(stdClass)#16 (14) {
["type"]=>
int(0)
["encoding"]=>
int(4)
["ifsubtype"]=>
int(1)
["subtype"]=>
string(4) "HTML"
["ifdescription"]=>
int(0)
["ifid"]=>
int(0)
["lines"]=>
int(123)
["bytes"]=>
int(4473)
["ifdisposition"]=>
int(1)
["disposition"]=>
string(10) "attachment"
["ifdparameters"]=>
int(1)
["dparameters"]=>
array(1) {
[0]=>
object(stdClass)#17 (2) {
["attribute"]=>
string(8) "filename"
["value"]=>
string(37) "message.htm"
}
}
["ifparameters"]=>
int(1)
["parameters"]=>
array(2) {
[0]=>
object(stdClass)#18 (2) {
["attribute"]=>
string(4) "name"
["value"]=>
string(37) "message.htm"
}
[1]=>
object(stdClass)#19 (2) {
["attribute"]=>
string(7) "charset"
["value"]=>
string(8) "us-ascii"
}
}
}
Can anyone give me a hint how can I access content of message.htm ?
Since the structure does not have any parts defined, then the message is "simple".
Try using:
$message = imap_fetchbody($inbox,$email_number,0);
This will fetch the "0th" part of the message, which should be the body.
Check out the docs here: http://www.php.net/manual/en/function.imap-fetchstructure.php

Publish on Twitter using PHP (OAuth) Abraham Williams

I'm at a certain time researching how to make the publication on twitter via programming, but until then I got the code I will show below, only that even with everything set up correctly still not sending, does anyone have any suggestions for settings I must be forgetting to do so sending is completed?
Remembering that I'm using the TwiterrOAuth Abraham Williams, already applied for the 1.1 API. (Latest version of GIT)
Below is the code.
<?php
// Insert your keys/tokens
$consumerKey = 'CONSUMER';
$consumerSecret = 'CSECRET';
$OAuthToken = 'TOKEN';
$OAuthSecret = 'TSECRET';
// Full path to twitterOAuth.php (change OAuth to your own path)
require_once('twitteroauth.php');
// create new instance
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $OAuthToken, $OAuthSecret);
// Your Message
$message = "This is a test message.";
// Send tweet
$tweet->post('statuses/update', array('status' => "$message"));
?>
Have researched in several posts here on the site and brought me no solution to my problem. Remembering that you are not returning anything, just nothing happens.
My application is setup as read and write on Twitter.
The $tweet->post return false if i check it.
This is what var_dump($tweet) returns
object(TwitterOAuth)#1 (13) {
["http_code"]=> int(0)
["url"]=> string(48) "https://api.twitter.com/1.1/statuses/update.json"
["host"]=> string(28) "https://api.twitter.com/1.1/"
["timeout"]=> int(30)
["connecttimeout"]=> int(30)
["ssl_verifypeer"]=> bool(false)
["format"]=> string(4) "json"
["decode_json"]=> bool(true)
["http_info"]=> array(20) {
["url"]=> string(48) "https://api.twitter.com/1.1/statuses/update.json"
["content_type"]=> NULL
["http_code"]=> int(0)
["header_size"]=> int(0)
["request_size"]=> int(0)
["filetime"]=> int(-1)
["ssl_verify_result"]=> int(0)
["redirect_count"]=> int(0)
["total_time"]=> float(30.02972)
["namelookup_time"]=> float(0.058814)
["connect_time"]=> float(0)
["pretransfer_time"]=> float(0)
["size_upload"]=> float(0)
["size_download"]=> float(0)
["speed_download"]=> float(0)
["speed_upload"]=> float(0)
["download_content_length"]=> float(-1)
["upload_content_length"]=> float(-1)
["starttransfer_time"]=> float(0)
["redirect_time"]=> float(0) }
["useragent"]=> string(25) "TwitterOAuth v0.2.0-beta2"
["sha1_method"]=> object(OAuthSignatureMethod_HMAC_SHA1)#2 (0) { }
["consumer"]=> object(OAuthConsumer)#3 (3) {
["key"]=> string(22) "uqZ5yUGoofxxxxxxxxxxx"
["secret"]=> string(40) "fGpJERhrIAB9RIyQEExxxxxxxxxxx"
["callback_url"]=> NULL
}
["token"]=> object(OAuthConsumer)#4 (3) {
["key"]=> string(50) "49596683-Sxxxxxxxxxxxxxxxxxx"
["secret"]=> string(40) "v3Q6pAeE4t1YXaGxxxxxxxxxxxxxx"
["callback_url"]=> NULL
}
}
The $host variable.
public $host = "https://api.twitter.com/1.1/";
Try adding ..
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $OAuthToken, $OAuthSecret)
$tweet->get('account/verify_credentials'); //<--- Add this.

Categories