Jump to content

Search the Community

Showing results for tags 'api'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

Found 13 results

  1. I am trying to use ChatGPT as the chatbot for my Magento 2 website, and I want to pass product data to it. To do this, I collected all the products and stored them in a JSON file, which I then read to embed the data in the `systemRoleContent` of the system role. However, the issue I am facing is that the JSON file is quite large. { "bot_response": "Error: ChatBot Error: Unexpected API response structure: {\n \"error\": {\n \"message\": \"Request too large for gpt-4o on tokens per min (TPM): Limit 30000, Requested 501140. The input or output tokens must be reduced in order to run successfully. Visit https://platform.openai.com/account/rate-limits to learn more.\",\n \"type\": \"tokens\",\n \"param\": null,\n \"code\": \"rate_limit_exceeded\"\n }\n}\n" } I noticed that there is a function that needs to be added to the API configuration, which allows you to run a query to select products based on keywords found in their names or descriptions that match keywords in the user’s message. The challenge is that users initially may not know the names of the products; they come to the chatbot to discover them. How can I address this issue? This is the code that I am working with right now: <?php namespace MetaCares\Chatbot\Model; use Magento\Framework\App\ObjectManager; class ChatBot { private $authorization; private $endpoint; private $conversationHistory = []; private $productsFile; private $fetchingDateFile; private $didFetchProducts = false; public function __construct() { $this->authorization = 'sk-proj-'; $this->endpoint = 'https://api.openai.com/v1/chat/completions'; $this->productsFile = __DIR__ . '/products.json'; $this->fetchingDateFile = __DIR__ . '/fetching_date.json'; $currentTime = time(); $timeDifferenceSeconds = 24 * 3600; if (!file_exists($this->fetchingDateFile)) { file_put_contents($this->fetchingDateFile, json_encode(['last_fetch_time' => 0])); } $fetchingData = json_decode(file_get_contents($this->fetchingDateFile), true); $lastFetchTime = $fetchingData['last_fetch_time'] ?? 0; if ($currentTime - $lastFetchTime > $timeDifferenceSeconds) { $products = $this->fetchProductsUsingModel(); $productsJson = json_encode($products); file_put_contents($this->productsFile, $productsJson); $fetchingData['last_fetch_time'] = $currentTime; file_put_contents($this->fetchingDateFile, json_encode($fetchingData)); $this->didFetchProducts = true; } $jsonSampleData = file_get_contents($this->productsFile); $systemRoleContent = <<<EOT Nom: Meta Cares Bot Description BOT Meta Cares répond aux questions sur les produits du site et fournit des conseils santé fiables. Tu aides les clients de Meta Cares à faire des choix éclairés tout en offrant un accompagnement personnalisé, sécurisé et adapté à leurs besoins. catalogue Meta Cares {$jsonSampleData} Liste des Sites Référencés : - PubMed : [https://pubmed.ncbi.nlm.nih.gov/](https://pubmed.ncbi.nlm.nih.gov/) - ScienceDirect : [https://www.sciencedirect.com/](https://www.sciencedirect.com/) --- - Génération d’images DALL·E : Désactivée EOT; $this->conversationHistory[] = [ 'role' => 'system', 'content' => $systemRoleContent ]; if (session_status() == PHP_SESSION_NONE) { session_start(); } if (isset($_SESSION['chat_history'])) { $this->conversationHistory = $_SESSION['chat_history']; } } public function fetchProductsUsingModel(): array { return $products; } private function getCategoryNames(array $categoryIds): array { return $categoryNames; } public function sendMessage(string $message): array { try { $this->conversationHistory[] = [ 'role' => 'user', 'content' => $message ]; $data = [ 'model' => 'gpt-4o', 'messages' => array_map(function ($msg) { return [ 'role' => $msg['role'] === 'bot' ? 'assistant' : $msg['role'], 'content' => $msg['content'] ]; }, $this->conversationHistory) ]; $response = $this->makeApiRequest($data); $arrResult = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new \Exception('Invalid API response format'); } if (!isset($arrResult['choices']) || !isset($arrResult['choices'][0]['message']['content'])) { throw new \Exception('Unexpected API response structure: ' . $response); } $assistantResponse = $arrResult['choices'][0]['message']['content']; $this->conversationHistory[] = [ 'role' => 'bot', 'content' => $assistantResponse ]; $_SESSION['chat_history'] = $this->conversationHistory; return [ "conversationHistory" => $_SESSION['chat_history'], 'didFetchProducts' => $this->didFetchProducts, 'response' => $assistantResponse, ]; } catch (\Exception $e) { throw new \Exception('ChatBot Error: ' . $e->getMessage()); } } private function makeApiRequest(array $data): string { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $this->endpoint, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'Authorization: Bearer ' . $this->authorization, ], CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0 ]); $response = curl_exec($ch); if (curl_errno($ch)) { $error = curl_error($ch); curl_close($ch); throw new \Exception('API request failed: ' . $error); } curl_close($ch); return $response; } }
  2. Hi everyone. I'm very new into self learning programming. Presently I'm trying to develop a simple basic Robot that would only Place a Market Order every seconds and it will cancel the Order every followed seconds. Using the following library: https://docs.b2bx.exchange/en/_docs/api-reference.html#private-api It would place Trade Order at a ( Price = ex.com api * Binance api Aggregate Trades Price) I have already wrote the api to call for xe.com exchange rate with php <?php $auth = base64_encode("username:password"); $context = stream_context_create([ "http" => [ "header" => "Authorization: Basic $auth" ] ]); $homepage = file_get_contents("https://xecdapi.xe.com/v1/convert_from?to=NGN&amount=1.195", false, $context ); $json = json_decode($homepage, TRUE); foreach ($json as $k=>$to){ echo $k; // etc }; ?> And also for the Binance Aggregate Price in JavaScript <script> var burl = "https://api3.binance.com"; var query = '/api/v3/aggTrades'; query += '?symbol=BTCUSDT'; var url = burl + query; var ourRequest = new XMLHttpRequest(); ourRequest.open('GET',url,true); ourRequest.onload = function(){ console.log(ourRequest.responseText); } ourRequest.send(); </script> My problem is how to handle these two api responds and also the functions to use them to place a trade and cancel it. Please help me out. Thanks in advance on any help.
  3. Hi I have a question about API keys and security. I am building a mobile app (learning) and will be using a PHP/MySQL JSON Rest API (designed myself) and I am new to APIs in general so some best practices would be appreciated if you have any? My real question is to do with securing these APIs. For example I was thinking of using user name and password that the user logs into the application with to be send over HTTPS for each request to validate the user is authorised and authenticated. However I have read that I should also be using API keys, so how would I integrate this in? Would each user have their own unique API key or would each system that uses this API have a unique key? If its each user that has their own key would I send all three pieces of data with the request (API Key, username and password). Any advice would be great. Thanks
  4. Trying to retrieve information from an API and display it in a table. <form action="dublinbus.php" method="get"> <h2>Current Dublin Bus Times.</h2> <b>Stop Number: </b><input type="number" name="stopid"></br></br> <input type="submit"> </form> ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ <?php $stopID = $_GET['stopid']; $url = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=" . $_GET['stopid'] . "&format=json"; // Process the JSON and check for errors $json = file_get_contents($url); $array = json_decode($json,true); if ($stopID != $array["stopid"]) { // Get the values for $errorCode and $errorMessage $errorCode = $array["errorcode"]; $errorMessage = $array["errormessage"]; echo "Error: "; echo $errorCode; echo $errorMessage; } else { // Get the values $duetime = $array["duetime"]; $destination = $array["destination"]; $route = $array["route"]; echo " <table>"; echo " <th>Stop Number</th><th>Route</th><th>Due Time</th><th>Destination</th>"; echo " <tr><td>" . $stopID . "</td><td>" . $route . "</td><td>" . $duetime . "</td><td>" . $destination . "</td></tr>"; echo "</table>"; } ?>
  5. Hello there.. I have a problem when loading comment from my database.. Here are working scripts which does not query the message/comment from database.. <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "responder"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //query the user table $sql = "SELECT * FROM user"; $result = $conn->query($sql); //get comment from array $comment = $_GET['comment'] + 1; //I want to replace below array comment with my database comment $ar = array( "Hello there.", "How are you?" ); require_once("facebook.php"); $config = array(); $config['appId'] = 'myapp'; $config['secret'] = 'mysecret'; $config['fileUpload'] = false; $fb = new Facebook($config); if ($result->num_rows > 0) { foreach ($result as $key) { $params = array( //long-live-token "access_token" => $key['offense_token'], //comment //need to replace this from database "message" => $ar[$comment], ); if($comment<10) { try { $ret = $fb->api('/my-comment-id/comments', 'POST', $params); echo 'Successfully posted to Facebook'; sleep(5); header('Location: set-comment.php?comment='.$comment); } catch(Exception $e) { echo $e->getMessage(); } } else{ echo "done"."<br>"; } } } ?> Above scripts working fine without querying from my database So my issues now, how do I query and loop each comment from database? Here my comment/message table.. TQ
  6. Hello everyone.. I have a question to delete comment based from user-id itself. I use PHP SDK to delete any comment to my facebook page and it was success as long as I specify the comment-id.. Below are my codes to delete a comment from comment-id $request = new FacebookRequest( $session, 'DELETE', '/{comment-id}' ); $response = $request->execute(); $graphObject = $response->getGraphObject(); Is it possible to delete comment based on user-id itself? I know that I just need to query the graph api to get the comment-id from A but each comment have different id`s so its hard to query the comment-id everytime.. For example: A, B, and C comment to my facebook post and I want to delete the comment where the user-id is from A? So, if the api scan and found out that A is commenting to my post, it will be deleted instead deleting B and C I really appreciate for any help from you guys.. Thanks
  7. Hi guys, I am having a little trouble getting my head around how to tackle an issue. I am working with an API :- https://www.photoshelter.com/developer/index/endpoints/public Connecting up to it no problem and getting the information via cURL is also no bother. The point is I am needing to loop through galleries to retrieve 400 gallery IDs so I can pass in the data I need so for example I execute my first cURL response which gives me all the gallery IDs from here :- /psapi/v3/collection/root/children Now then I need to run a foreach loop to get each gallery ID to pass to :- /psapi/v3/gallery/{gallery_id} /psapi/v3/gallery/{gallery_id}/key_image Now the problem is I am having to use cURL to get the JSON data from here too and then finally the last one :- /psapi/v3/gallery/{gallery_id}/images/{image_id} To get the gallery featured image. Now the first cURL works fine but when I introduce the others in foreach loops it cripples it on loading time, but looking through of course it would as its excuting cURL a ridiculous amount of times. Is there a better way of tackling an issue like this as I feel cURL and file_get_contents is the wrong way going about this. Normally it's one execution and I get all the data I have never worked with something like this before. I would show my code but I feel it is unnecessary at this point on the grounds of I do not think this is the most productive way of even looking at this Currently the only thing I can think of is creating a query string to execute via a CRON job that would execute twice a day to check through the galleries API at Photoshelter and add everything to a database that I need. Any information would be greatly appreciated Thanks in advance Jamie
  8. I am looking to do something like this. Showing multiple locations of a business on Google Maps. Living Social has it and so does Groupon. https://www.livingsocial.com/ca/cities/83-ottawa/deals/1542906-basic-training-style-boot-camp?append_ref_code=home_whats_new I know it can be done manually but since it's a user based website, how would the user(business)'s added locations correspond with the Google Maps? Can you point me in the right direction?
  9. Hello, I have an Internet Radio station and I use Shoutcast. I have a function that allows me to grab the song and artist information such as Del Amitri - Roll To Me and show it on my website, and automatically changing when the songs change. I show the now playing, and last three songs. I'm wondering How I can get it to also pull in album artwork from Last.FM or Amazon such as this website: BIG 106.5 - Dayton's 70s & 80s Hits (move over the black bar and drop down). You will be able to see something such that I would want to accomplish. Not sure if this merely Javascript, or if there's also PHP.. but then again, I'd think Javascript for it to automatically change when a new song plays. Here is the file I currently have setup...which pulls the information from my shoutcast stream. I would love to incorporate album art from Amazon and/or an internal database that I have setup.. Here is what the file currently looks like. I also have stuff commented out for which I am not using ATTM. It pulls the song like artist - title <!--<html> <head>--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script> <script src="http://wlqtdb.com/wayne/pollstation.js" type="text/javascript"></script> <!--</head> <body>--> Now Playing on WLQT-DB: <!--<div id="currentsong"> </div>--> <span id="currentsong"></span> Recently Played: <!--<table> <tr><th>Recently Played Songs</th></tr> <tr><td><img id='prevsong1' alt=""><span id="prevsong1"></span></td></tr> <tr><td><span id="prevsong2"></span></td></tr> <tr><td><span id="prevsong3"></span></td></tr>--> <span id="prevsong1"></span> <span id="prevsong2"></span> <span id="prevsong3"></span> <!--<tr><td><span id="prevsong4"></span></td></tr> <tr><td><span id="prevsong5"></span></td></tr> <tr><td><span id="prevsong6"></span></td></tr> <tr><td><span id="prevsong7"></span></td></tr> <tr><td><span id="prevsong8"></span></td></tr> <tr><td><span id="prevsong9"></span></td></tr> <tr><td><span id="prevsong10"></span></td></tr>--> <!-- </table> Testing: <? echo "$currentsong"; ?> </body> </html>--> Any help would be greatly appreciated. As you can see with this result, I do the Current playing song, then it does the last 3 songs. Thanks
  10. I get funny result from my * echo $item['text']; * I do get the strings I intend to. Eg. I would like to have or sholud get the result: /Barrafina Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here. Matt Ta-Min/ But instead I get /Barrafina ee Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here. 5 5 E Eu uh h Matt Ta-Min / What did I do wrong? here is the code: If you have time and energy to look the JSON you will see from where eg.5 5 E Eu uh h.. comes. I appreciate any help. This is too strange for me. $json_results = json_decode($results,true); //var_dump($json_results); $items0 = $json_results['response']['groups']['0']['items']['0']; $items1 = $json_results['response']['groups']['0']['items']['0']['tips']; $items2 = $json_results['response']['groups']['0']['items']['0']['tips']['0']; //<div style="align:center;"> foreach ( $items0+$items1 as $item){ echo '<li>'; echo $item['name']; echo $item['text']; } foreach ( $items2 as $item){ print $item['firstName']; print '&nbsp'; print $item['lastName']; } Here is encode JSON array(2) { ["meta"]=> array(2) { ["code"]=> int(200) ["requestId"]=> string(24) "55fb1f91498e70ad2e246eed" } ["response"]=> array(10) { ["suggestedFilters"]=> array(2) { ["header"]=> string(12) "Tap to show:" ["filters"]=> array(2) { [0]=> array(2) { ["name"]=> string(13) "With specials" ["key"]=> string( "specials" } [1]=> array(2) { ["name"]=> string( "Open now" ["key"]=> string(7) "openNow" } } } ["geocode"]=> array( { ["what"]=> string(0) "" ["where"]=> string(6) "london" ["center"]=> array(2) { ["lat"]=> float(51.50853) ["lng"]=> float(-0.12574) } ["displayString"]=> string(38) "London, Greater London, United Kingdom" ["cc"]=> string(2) "GB" ["geometry"]=> array(1) { ["bounds"]=> array(2) { ["ne"]=> array(2) { ["lat"]=> float(51.691643999656) ["lng"]=> float(0.33418999705203) } ["sw"]=> array(2) { ["lat"]=> float(51.284674044171) ["lng"]=> float(-0.50855792793694) } } } ["slug"]=> string(6) "london" ["longId"]=> string(17) "72057594040571679" } ["warning"]=> array(1) { ["text"]=> string(114) "There aren't a lot of results near you. Try something more general, reset your filters, or expand the search area." } ["headerLocation"]=> string(6) "London" ["headerFullLocation"]=> string(6) "London" ["headerLocationGranularity"]=> string(4) "city" ["query"]=> string(4) "food" ["totalResults"]=> int(246) ["suggestedBounds"]=> array(2) { ["ne"]=> array(2) { ["lat"]=> float(51.510800358799) ["lng"]=> float(-0.12174369837641) } ["sw"]=> array(2) { ["lat"]=> float(51.508100699014) ["lng"]=> float(-0.13015278468604) } } ["groups"]=> array(1) { [0]=> array(3) { ["type"]=> string(18) "Recommended Places" ["name"]=> string(11) "recommended" ["items"]=> array(1) { [0]=> array(4) { ["reasons"]=> array(2) { ["count"]=> int(0) ["items"]=> array(1) { [0]=> array(3) { ["summary"]=> string(20) "This spot is popular" ["type"]=> string(7) "general" ["reasonName"]=> string(23) "globalInteractionReason" } } } ["venue"]=> array(17) { ["id"]=> string(24) "53bab96d498e7e355fb53d6c" ["name"]=> string(9) "Barrafina" ["contact"]=> array(6) { ["phone"]=> string(13) "+442074401456" ["formattedPhone"]=> string(16) "+44 20 7440 1456" ["twitter"]=> string(13) "barrafinaadst" ["facebook"]=> string(15) "705351912878392" ["facebookUsername"]=> string(23) "BarrafinaAdelaideStreet" ["facebookName"]=> string(25) "Barrafina Adelaide Street" } ["location"]=> array(10) { ["address"]=> string(14) "10 Adelaide St" ["crossStreet"]=> string(13) "William IV St" ["lat"]=> float(51.509450528906) ["lng"]=> float(-0.12594824153122) ["postalCode"]=> string( "WC2N 4HZ" ["cc"]=> string(2) "GB" ["city"]=> string(6) "London" ["state"]=> string(14) "Greater London" ["country"]=> string(14) "United Kingdom" ["formattedAddress"]=> array(5) { [0]=> string(30) "10 Adelaide St (William IV St)" [1]=> string(6) "London" [2]=> string(14) "Greater London" [3]=> string( "WC2N 4HZ" [4]=> string(14) "United Kingdom" } } ["categories"]=> array(1) { [0]=> array(6) { ["id"]=> string(24) "4bf58dd8d48988d150941735" ["name"]=> string(18) "Spanish Restaurant" ["pluralName"]=> string(19) "Spanish Restaurants" ["shortName"]=> string(7) "Spanish" ["icon"]=> array(2) { ["prefix"]=> string(52) "https://ss3.4sqi.net/img/categories_v2/food/spanish_" ["suffix"]=> string(4) ".png" } ["primary"]=> bool(true) } } ["verified"]=> bool(false) ["stats"]=> array(3) { ["checkinsCount"]=> int(357) ["usersCount"]=> int(278) ["tipCount"]=> int(26) } ["url"]=> string(22) "http://barrafina.co.uk" ["price"]=> array(3) { ["tier"]=> int(2) ["message"]=> string( "Moderate" ["currency"]=> string(2) "£" } ["rating"]=> float(9) ["ratingColor"]=> string(6) "00B551" ["ratingSignals"]=> int(80) ["allowMenuUrlEdit"]=> bool(true) ["hours"]=> array(2) { ["status"]=> string(19) "Open until 11:00 PM" ["isOpen"]=> bool(true) } ["specials"]=> array(2) { ["count"]=> int(0) ["items"]=> array(0) { } } ["photos"]=> array(2) { ["count"]=> int(31) ["groups"]=> array(0) { } } ["hereNow"]=> array(3) { ["count"]=> int(0) ["summary"]=> string(11) "Nobody here" ["groups"]=> array(0) { } } } ["tips"]=> array(1) { [0]=> array(9) { ["id"]=> string(24) "55db9142498ede18f5b31b81" ["createdAt"]=> int(1440452930) ["text"]=> string(164) "Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here." ["type"]=> string(4) "user" ["canonicalUrl"]=> string(52) "https://foursquare.com/item/55db9142498ede18f5b31b81" ["likes"]=> array(3) { ["count"]=> int(2) ["groups"]=> array(0) { } ["summary"]=> string(7) "2 likes" } ["logView"]=> bool(true) ["todo"]=> array(1) { ["count"]=> int(0) } ["user"]=> array(5) { ["id"]=> string( "98683884" ["firstName"]=> string(4) "Matt" ["lastName"]=> string(6) "Ta-Min" ["gender"]=> string(4) "male" ["photo"]=> array(2) { ["prefix"]=> string(31) "https://irs1.4sqi.net/img/user/" ["suffix"]=> string(30) "/98683884-1MJ0OTISTPZWSBRJ.jpg" } } } } ["referralId"]=> string(30) "e-3-53bab96d498e7e355fb53d6c-0" } } } } } } Here is JSON {"meta":{"code":200,"requestId":"55fbde58498e7fdbd12f8fb2"},"response":{"suggestedFilters":{"header":"Tap to show:","filters":[{"name":"With specials","key":"specials"},{"name":"Open now","key":"openNow"}]},"geocode":{"what":"","where":"london","center":{"lat":51.50853,"lng":-0.12574},"displayString":"London, Greater London, United Kingdom","cc":"GB","geometry":{"bounds":{"ne":{"lat":51.691643999655895,"lng":0.33418999705203406},"sw":{"lat":51.28467404417054,"lng":-0.5085579279369435}}},"slug":"london","longId":"72057594040571679"},"warning":{"text":"There aren't a lot of results near you. Try something more general, reset your filters, or expand the search area."},"headerLocation":"London","headerFullLocation":"London","headerLocationGranularity":"city","query":"food","totalResults":246,"suggestedBounds":{"ne":{"lat":51.5108003587992,"lng":-0.12174369837640672},"sw":{"lat":51.50810069901375,"lng":-0.1301527846860385}},"groups":[{"type":"Recommended Places","name":"recommended","items":[{"reasons":{"count":0,"items":[{"summary":"This spot is popular","type":"general","reasonName":"globalInteractionReason"}]},"venue":{"id":"53bab96d498e7e355fb53d6c","name":"Barrafina","contact":{"phone":"+442074401456","formattedPhone":"+44 20 7440 1456","twitter":"barrafinaadst","facebook":"705351912878392","facebookUsername":"BarrafinaAdelaideStreet","facebookName":"Barrafina Adelaide Street"},"location":{"address":"10 Adelaide St","crossStreet":"William IV St","lat":51.50945052890648,"lng":-0.1259482415312226,"postalCode":"WC2N 4HZ","cc":"GB","city":"London","state":"Greater London","country":"United Kingdom","formattedAddress":["10 Adelaide St (William IV St)","London","Greater London","WC2N 4HZ","United Kingdom"]},"categories":[{"id":"4bf58dd8d48988d150941735","name":"Spanish Restaurant","pluralName":"Spanish Restaurants","shortName":"Spanish","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/spanish_","suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":357,"usersCount":278,"tipCount":26},"url":"http:\/\/barrafina.co.uk","rating":9.0,"ratingColor":"00B551","ratingSignals":80,"allowMenuUrlEdit":true,"hours":{"status":"Closed until Noon","isOpen":false},"specials":{"count":0,"items":[]},"photos":{"count":31,"groups":[]},"hereNow":{"count":0,"summary":"Nobody here","groups":[]}},"tips":[{"id":"55db9142498ede18f5b31b81","createdAt":1440452930,"text":"Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here.","type":"user","canonicalUrl":"https:\/\/foursquare.com\/item\/55db9142498ede18f5b31b81","likes":{"count":2,"groups":[],"summary":"2 likes"},"logView":true,"todo":{"count":0},"user":{"id":"98683884","firstName":"Matt","lastName":"Ta-Min","gender":"male","photo":{"prefix":"https:\/\/irs1.4sqi.net\/img\/user\/","suffix":"\/98683884-1MJ0OTISTPZWSBRJ.jpg"}}}],"referralId":"e-3-53bab96d498e7e355fb53d6c-0"}]}]}}
  11. Would like some thoughts about this autoloader for namespaces. Its loosely based on Zend Framework 2 using Composer. I wanted a simple loader for including my custom classes(ie DB connection, list and forms generations etc) in application modules. Autoloader works as expected so no error to debug, but looking more for improvements or gotcha's I'm not aware of. This is pseudo code, but the machinery is what's important. ./controller_script.php /* initializes Autoload with an array of namespace strings */ include 'init_autoloader.php'; /* from testspaces.php */ echo Testspaces\Autoload\Tsclass::printSomething(); // outputs This is a simple string. /* from globalspaces.php */ echo Globalspaces\Autoload\Omnipresent::imEverywhere(); //outputs This is a good hand. ./init_autoloader.php /** * initialize the autoloader for namespaces under the lib directory. * this script would be placed in each module where global classes * were required, ie DB connections, UI output(lists and forms) */ /* namespaces array, namespace file name matches first part before first backslash */ $nsarray = array( 'Globalspaces\Autoload\Omnipresent', 'Testspaces\Autoload\Tsclass', ); /* initialize the AutoloaderInit class */ $apath = __DIR__ . "/lib/autoload.php"; if (file_exists($apath)) { include $apath; $loaderObj = new AutoloaderInit($nsarray); $loaderObj->getLoader(); } else { echo "Missing autoload.php script, check file path: ".$apath."<br>"; } lib/autoload.php class AutoloaderInit { private static $loader; private static $nsnames; // indexed array of namespace strings defined in init_autoloader public function __construct($nsarray) { self::$nsnames = $nsarray; } /* * callback function called by spl_autoload_register * $class passed by reference */ public static function loadClassLoader($class) { if ($class) { $nameparts = explode('\\', $class); $filename = strtolower($nameparts[0]).".php"; require __DIR__ . DIRECTORY_SEPARATOR . $filename; } else { throw new Exception("loadClassLoader failed to include ".$filename); } } /* * interface method called from initializer * $params array $nsnames, array of namespace strings * $return void */ public static function getLoader() { //error_log("getLoader nsnames: ".var_dump(self::$nsnames)); if (self::$nsnames) { $cnt = count(self::$nsnames); for($i=0;$i<=$cnt;$i++) { if (null !== self::$loader) return self::$loader; spl_autoload_register(array('AutoloaderInit', 'loadClassLoader'), true, true); self::$loader = $loader = new self::$nsnames[$i]; // new instance of class } // close for loop spl_autoload_unregister(array('AutoloaderInit', 'loadClassLoader')); return $loader; } else { error_log("No namespaces provided to getLoader"); } } } lib/testspace.php namespace Testspaces\Autoload; /* a class defined in namespace */ class Tsclass { static function printSomething() { echo "This is a simple string.<br>"; } } lib/globalspaces.php namespace Globalspaces\Autoload; /* another class defined in namespace */ class Omnipresent { static function imEverywhere() { echo "This is a good hand.<br>"; } }
  12. I've created a php code that automatically pulls post that are assigned to a category (dailydose) from my wordpress site and creates a daily mailchimp campaign using a email template. I now want to be able to pull ads that are assiocated with each post. So I'm stuck on how I can make that happen please help!! functions.php //wp_schedule_event( 1428610800, 'hourly', 'daily_dose_mailer' ); //wp_unschedule_event( time(), 'hourly', 'daily_dose_mailer' ); //wp_clear_scheduled_hook( 'daily_dose_mailer' ); add_action( 'daily_dose_mailer', 'daily_doser' ); function daily_doser(){ $cur_day = date( "w", time()); $standard_order = array("1","2","3","4","5"); if($cur_day >= 1 && $cur_day <= 5){ require_once 'includes/mailchimp-mailchimp-api-php-190cf58000ee/src/Mailchimp.php'; //Get content $custom_query = new WP_Query(array('post_type'=>'post','posts_per_page'=>5,'cat'=>1279)); $content = array(); $std_count = 0; while($custom_query->have_posts()) : $custom_query->the_post(); $image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'single-post-thumbnail' ); if(get_post_meta(get_the_ID(),"dd_order",true) != "") $content[get_post_meta(get_the_ID(),"dd_order",true)] = array("title"=>get_the_title(),"summary"=>get_the_excerpt(),"link"=>get_permalink(),"image"=>$image[0]); else $content[$standard_order[$std_count]] = array("title"=>get_the_title(),"summary"=>get_the_excerpt(),"link"=>get_permalink(),"image"=>$image[0]); $std_count++; endwhile; $content_with_html = ''; $count = 1; $ad_count = 0; if($cur_day == 1) $ad_order = array("4","5","6","7","8"); if($cur_day == 2) $ad_order = array("8","4","5","6","7"); if($cur_day == 3) $ad_order = array("7","8","4","5","6"); if($cur_day == 4) $ad_order = array("6","7","8","4","5"); if($cur_day == 5) $ad_order = array("5","6","7","8","4"); foreach($content as $cont){ if(function_exists("wp_template_ad")) { $ad = wp_template_ad($ad_order[$ad_count]); } if($count == 1){ $content_with_html .= ' <tr> <td> <table style="width: 600px; margin: 10px 0;" width="600px"> <tbody> <tr> <td style="padding: 0px 0;"> <a href="'.$content[strval($count)]["link"].'" style="border-collapse: collapse; display: block; font-family: Arial Black, Gadget, sans-serif; font-weight: 900; font-size: 26px; line-height: 28px; color: #03030B; letter-spacing: -.03em; text-decoration: none;">'.$content[strval($count)]["title"].'</a> <a href="'.$content[strval($count)]["link"].'" style="text-decoration: none;float:right;" target="_blank"><img src="'.$content[strval($count)]["image"].'" style="width: 250px; min-height: 165px;" width="250" width="250" /></a> <p style="line-height: 18px; font-size: 12px; font-family: Georgia; margin: 0; padding: 0;"> <span style="font-size: 15px; line-height: 19px;">'.$content[strval($count)]["summary"].'</span><br><a href="'.$content[strval($count)]["link"].'" style="font-size: 14px; text-decoration: none; font-weight: bold; font-family: Arial Black, Gadget, sans-serif; color: #da1f3e;" target="_blank">READ MORE</a></p> </td> </tr> </tbody> </table> </td> </tr> <tr align="center"> <td bgcolor="#f3f3f3" style="background-color: #f3f3f3;"> '.$ad.'</td> </tr> <tr> <td> <img alt="" src="http://dsnews.com/wp-content/uploads/sites/25/2014/01/Solid-Line.jpg" style="display: block; border: 0px solid; text-align: center; width: 600px; min-height: 9px;" width="600" width="600" /> <!--AD GOES HERE--> <img alt="" src="http://dsnews.com/wp-content/uploads/sites/25/2014/01/Solid-Line.jpg" style="display: block; border: 0px solid; text-align: center; width: 600px; min-height: 9px;" width="600" width="600" /></td> </tr> '; }else{ $content_with_html .= ' <tr> <td style="padding: 13px 0;"> <a href="'.$content[strval($count)]["link"].'" style="border-collapse: collapse; display: block; font-family: Arial Black, Gadget, sans-serif; font-weight: 900; font-size: 20px; line-height: 24px; color: #03030B; letter-spacing: -.03em; text-decoration: inherit;">'.$content[strval($count)]["title"].'</a> <p style="line-height: 18px; font-size: 12px; font-family: Georgia; margin: 0; padding: 0;"> <span style="font-size: 12px; line-height: 18px;">'.$content[strval($count)]["summary"].'</span><br><a href="'.$content[strval($count)]["link"].'" style="font-size: 11px; text-decoration: none; font-weight: bold; font-family: Arial Black, Gadget, sans-serif; color: #da1f3e;" target="_blank">READ MORE</a></p> </td> </tr> <tr align="center"> <td bgcolor="#f3f3f3" style="background-color: #f3f3f3;"> '.$ad.'</td> </tr> <tr> <td> <img alt="" src="http://dsnews.com/wp-content/uploads/sites/25/2014/01/Solid-Line.jpg" style="display: block; border: 0px solid; text-align: center; width: 600px; min-height: 9px;" width="600" width="600" /> <!--AD GOES HERE--> <img alt="" src="http://dsnews.com/wp-content/uploads/sites/25/2014/01/Solid-Line.jpg" style="display: block; border: 0px solid; text-align: center; width: 600px; min-height: 9px;" width="600" width="600" /></td> </tr> '; } $count++; $ad_count++; } /*$content_with_html .= ' <tr align="center"> <td class="spacer"> '. wp_templol($ad_order[$ad_count]).'</td> </tr> ';*/ $MC = new Mailchimp('01a1ecf38bc12fdc975ff0c569945244-us1'); //Pseudo code //Grab the list that it will be sent to //lists/members (string apikey, string id, string status, struct opts) //Create markup of email - this also assigns the appropriate list //campaigns/create (string apikey, string type, struct options, struct content, struct segment_opts, struct type_opts) $retval = $MC->call('campaigns/create', array( "type"=>"regular", "options"=> array("list_id"=>"1924082bfe", "subject"=>"Your Daily Dose from DS News", "from_name"=>"DSNews", "from_email"=>"[email protected]", "inline_css"=>true), "content"=> array("html"=>' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Your Daily Dose of DS News</title> </head> <body> <div align="left" style="text-align: left; font-size: 12px; font-family: Century Gothic,Georgia,Verdana; padding-bottom: 50px !important;"> <table border="0" cellpadding="0" cellspacing="0" style="width: 100%; margin: 0px;" width="728"> <tbody> <tr> <td align="center" bgcolor="#fff" colspan="2" style="padding: 5px; text-align: center;"> Email not displaying correctly? <a href="*|ARCHIVE|*">Display this email in your browser</a></td> </tr> <tr> <td align="center" bgcolor="#000" colspan="2" style="text-align: center; background-color: #000;"> <img alt="" height="30" src="http://admin.dsnews.com/editor_images/image_19b6f173/column.gif" style="width: 15px; min-height: 30px;" width="15" width="15" /> <table align="center" bgcolor="#000000" border="0" cellpadding="0" cellspacing="10px" width="600"> <tbody> <tr align="center" style="width: 600px;"> <td align="center" bgcolor="#FFF" style="padding: 0 0px; font-size: 12px; text-transform: uppercase; text-align: left; font-weight: bold; color: #fe0000; background-color: #000; font-family: Arial, Helvetica, sans-serif;"> *|DATE:l, M j, Y|*</td> <td align="right" bgcolor="#8a8b8a" style="font-size: 12px; text-transform: uppercase; padding: 0 0px; text-align: right; font-weight: bold; color: #fff; background-color: #000;"> <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e247987c4a6efb818978c" style="font-size: 12px; text-decoration: none; text-align: right; font-family: Arial Black, Gadget, sans-serif; color: #fff; background-color: #000; letter-spacing: .003em;" target="_blank">HOME</a> | <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e24791b911a59d15e5063" style="font-size: 12px; text-decoration: none; text-align: right; font-family: Arial Black, Gadget, sans-serif; color: #fff; background-color: #000;" target="_blank">CONTACT US</a> | <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e2479f018cfa44911db10" style="font-size: 12px; text-decoration: none; text-align: right; font-family: Arial Black, Gadget, sans-serif; color: #fff; background-color: #000;" target="_blank">MAGAZINE</a><a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e2479c6b1632e3f8df548" style="text-decoration: none; color: #000;" target="_blank"> </a>| <em><a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e2479ac6f4a1f6d5178c8" style="font-size: 12px; text-decoration: none; text-align: right; font-family: Arial Black, Gadget, sans-serif; color: #fff; background-color: #000;" target="_blank">SUBSCRIBE</a></em></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table align="center" border="0" cellpadding="0" cellspacing="0" style="width: 600px; margin: 0px auto;"> <tbody> <tr> <td width="600"> <div align="center" style="text-align: center;"> </div> <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e2479b35fafb4d42723f5" style="text-decoration: none;" target="_blank"><img alt="DSNews.com | Daily Dose" height="109" src="http://dsnews.com/wp-content/uploads/sites/25/2014/01/Daily-Dose.jpg" style="display: block; border: 0px solid; text-align: center; width: 600px; min-height: 123px;" width="600" width="600" /></a></td> </tr> <tr> <td> <div align="center" style="text-align: center;"> </div> <img alt="" src="http://dsnews.com/wp-content/uploads/sites/25/2014/01/Solid-Line.jpg" style="display: block; border: 0px solid; text-align: center; width: 600px; min-height: 9px;" width="600" width="600" /></td> </tr> <tr> <td> <table style="width: 600px; margin: 0;"> <tbody> <tr> <td align="center" style="padding: 0px 0; text-align: center;"> <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e24799b979aa344545f8a" style="border-collapse: collapse; font-family: Arial Black, Gadget, sans-serif; font-size: 10px; color: #03030B; letter-spacing: -.003em; text-decoration: none;"> DSNEWS.COM</a> | <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e2479db831868790c2639" style="border-collapse: collapse; font-family: Arial Black, Gadget, sans-serif; font-size: 10px; color: #03030B; letter-spacing: -.003em; text-decoration: inherit;">REOREDBOOK</a>| <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e2479d269f0e3591d670f" style="border-collapse: collapse; font-family: Arial Black, Gadget, sans-serif; font-size: 10px; color: #03030B; letter-spacing: -0.03em; text-decoration: inherit;">BLACK BOOK</a> | <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e247903105127fafb9dbc" style="border-collapse: collapse; font-family: Arial Black, Gadget, sans-serif; font-size: 10px; color: #03030B; letter-spacing: -.003em; text-decoration: inherit;">FORCE</a> | <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e247907d4c0d59b488676" style="border-collapse: collapse; font-family: Arial Black, Gadget, sans-serif; font-size: 10px; color: #03030B; letter-spacing: -.003em; text-decoration: inherit;">GOVERNMENT FORUM</a> | <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e247905ea889cdfee43cf" style="border-collapse: collapse; font-family: Arial Black, Gadget, sans-serif; font-size: 10px; color: #03030B; letter-spacing: -.003em; text-decoration: inherit;">FIVE STAR CONFERENCE</a></td> </tr> </tbody> </table> </td> </tr> <tr> <td> <img alt="" src="http://dsnews.com/wp-content/uploads/sites/25/2014/01/Solid-Line.jpg" style="display: block; border: 0px solid; text-align: center; width: 600px; min-height: 9px;" width="600" width="600" /></td> </tr> '.$content_with_html.' <tr> <td> </td> </tr> </tbody> </table> <table bgcolor="#f3f3f3" border="0" cellpadding="0" cellspacing="0" style="margin: 10px auto;" width="100%"> <tbody> <tr> <td> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600"> <tbody> <tr> <td colspan="2"> <table style="width: 600px; margin: 10px auto;"> <tbody> <tr> <td align="center" style="width: 200px; text-align: center; padding-right: 5px;"> <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e24793af4e6a183b3ef6f" style="font-size: 9px; text-decoration: none; color: #8a8b8a;" target="_blank"><img alt="DSNews" height="50" src="http://dsnews.com/wp-content/uploads/sites/25/2014/01/ds.jpg" width="50" /></a></td> </tr> </tbody> </table> </td> </tr> <tr> <td align="center" style="font-size: 9px; text-align: left; color: #8a8b8a; border-top-color: #000; padding: 10px 0; border-top-style: groove; border-top-width: 2px;" width="280"> <strong style="color: #67c7d3; font-weight: normal;">Corporate Offices</strong> | Phone: 800.856.8060<br /> 1909 Woodall Rodgers, Suite 300 Dallas, Texas 75201</td> <td align="center" style="font-size: 9px; text-align: right; color: #8a8b8a; border-top-color: #000; padding: 10px 0; border-top-style: groove; border-top-width: 2px;" width="320"> <strong style="color: #67c7d3; font-weight: normal;">Washington Bureau</strong> | Phone: 202.393.5511<br /> 1101 Pennsylvania Ave. NW, Suite 600 | Washington, D.C. 20004</td> </tr> </tbody> </table> <table align="center" border="0" cellpadding="0" cellspacing="0" width="600"> <tbody> <tr> <td align="center" colspan="2" style="color: #8a8b8a; padding: 10px 0px; font-size: 7px; border-bottom-width: 1px; border-bottom-style: dotted; border-bottom-color: #252722; text-align: center;"> You are receiving this e-mail because you opted in at our Web site DSNews.com or attended a Five Star Conference. Copyright 2009 DS News. All rights reserved.<br /> <a href="*|UNSUB|*" style="text-decoration: none; color: #000000; " target="_blank">Unsubscribe.</a> <span style="line-height: 11.199999809265137px;">*|EMAIL|*<span style="font-size: 7px; line-height: 1.6em;"> from this list.</span></span></td> </tr> <tr> <td align="center" colspan="2"> <table style="width: 600px;"> <tbody> <tr> <td align="center" style="text-align: center;"> <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e247963cf5f9844f5a817" style="font-size: 9px; text-decoration: none; color: #8a8b8a;" target="_blank">DSNews.com</a></td> <td align="center" style="text-align: center;"> <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e2479c36851c1fe0a7a08" style="font-size: 9px; text-decoration: none; color: #8a8b8a;" target="_blank">REORedBook</a></td> <td align="center" style="text-align: center;"> <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e2479f47338dd7e641363" style="font-size: 9px; text-decoration: none; color: #8a8b8a;" target="_blank">BlackBook</a></td> <td align="center" style="text-align: center;"> <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e2479b6f3467ce75a656b" style="font-size: 9px; text-decoration: none; color: #8a8b8a;" target="_blank">TheFiveStar.com</a></td> <td align="center" style="text-align: center;"> <a href="http://link.dsnews.com/c/443/75a98e997857ea44b0bc30da975bb0f12b9e4c97445e24790cdf2f599aba04c2" style="font-size: 9px; text-decoration: none; color: #8a8b8a;" target="_blank">FORCE</a></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div> <br /> </body> </html> ') ) ); //Send it out //campaigns/send-test (string apikey, string cid, array test_emails, string send_type) - this will be replace by normal send // echo $retval; } }
  13. I have code where I'm simply calling an API and I've converted it to loop the call so that I can call it with three different argument values. This is because the API is structured where it can accept one value for that argument at a time, but I need to compare the results of the three calls and I think the best way is to build a single array from the responses by either pushing a value if it exists or pushing the whole index if not. Think of it like the API response can give me data that can be as much as 400 products that are sold across 3 stores. All 400 may be sold in one store, but maybe only 120 in another and 100 in the third. I need my array to be all 400 products but I'll want to have an array within that holds the stores for the given product. Code: $IdentifierTest = 1472; $arguments = ['store 1', 'store 2', 'store 3']; $TestApi = app(TestApi::class); $newArray = array(); foreach($arguments as $argument){ $testResponse = $TestApi->getData($IdentifierTest, $argument); $Data = $testResponse->getResult()->getData(); // get the final results of call //check if array empty, and if so, push all records // if not empty, start checking 'id' against existing array records. If match, push stores. If not, add record to array } $this->makeFile($IdentifierTest, $Data); An example of the response is: array:426 [▼ 0 => prices {#2698 ▼ #container: array:11 [▼ "prd" => 2380 "id" => "173489" "price" => "65.00" ] } The issue is that specific example only shows up when calling the API with 'store 1' and 'store 2' as the argument, but not 'store 3'. What I'd like to do is call the API with each argument and create a new array with a ```stores``` index that pushes the store number if the id exists in the call, like so: array:426 [▼ 0 => prices {#2698 ▼ #container: array:11 [▼ "prd" => 2380 "id" => "173489" "price" => "65.00" stores: array[ 'store 1', 'store 2' ] ] } So when it's called with 'store 1' I would push the response into an array with 'store 1' as the value in 'stores', then on 'store 2' I would take the response and first check to see if the id exists in the array I've made. If it exists, I'll add 'store 2' to the 'stores' and if not I'll make a new index in the array. Basically, if product (id) 178293 is sold in all three stores then that means it would come back in all 3 API response calls and would end up being a single record in this new array with ```stores['store 1', 'store 2', 'store 3']``` How can I create a new array from this where I push only the stores if the id exists in the API call while keeping the current structure?
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.