{"id":20765796,"url":"https://github.com/rkrehn/claudephp","last_synced_at":"2025-08-15T22:43:32.755Z","repository":{"id":232327303,"uuid":"784051756","full_name":"rkrehn/claudephp","owner":"rkrehn","description":"This is a tutorial on how to integrate Claude AI with PHP","archived":false,"fork":false,"pushed_at":"2024-04-09T05:42:56.000Z","size":15,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-11-17T11:19:29.647Z","etag":null,"topics":["ai","claude","claude-ai","claude-api","php","tutorial","tutorial-code"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rkrehn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-04-09T05:01:51.000Z","updated_at":"2024-10-14T11:55:27.000Z","dependencies_parsed_at":null,"dependency_job_id":"ee3dc65e-9398-47fd-b6f5-c7d9986dff5e","html_url":"https://github.com/rkrehn/claudephp","commit_stats":null,"previous_names":["rkrehn/claudephp"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fclaudephp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fclaudephp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fclaudephp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rkrehn%2Fclaudephp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rkrehn","download_url":"https://codeload.github.com/rkrehn/claudephp/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234470341,"owners_count":18838636,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","claude","claude-ai","claude-api","php","tutorial","tutorial-code"],"created_at":"2024-11-17T11:19:00.462Z","updated_at":"2025-01-18T06:12:48.292Z","avatar_url":"https://github.com/rkrehn.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# About\nThis guide is designed to teach people how to use Claude AI by Anthropic using a basic \"I want one response\" in PHP. This code is used in my travel itinerary generation website [ReisPlan](https://www.reisplan.net) after I migrated it away from ChatGPT. I love how PHP handles JSON and XML data, so this tutorial is a bit easier. I'll be using curl for sending the data.\n\n# Setup\n\nDeclare your API key (insert your [Claude AI API key](https://console.anthropic.com/dashboard) in the quotes)\n\n```PHP\n// API endpoint URL\n$url = 'https://api.anthropic.com/v1/messages';\n\n// Your OpenAI API key\n$apiKey = '[API KEY]';\n```\n\n# Setting up the request\n\nThe following code creates the JSON request to Claude AI. You can review all the options you can include here: [https://docs.anthropic.com/claude/reference/messages_post](https://docs.anthropic.com/claude/reference/messages_post).\n\nIt's worth noting that only the \"model\", \"messages\", and \"max_tokens\" are required in the body. There are [many models](https://docs.anthropic.com/claude/docs/models-overview), but I'm using **claude-instant-1.2** in this example. Likewise, there are a few roles you can use such as system, user, assistance, or function. Typically, the **system** role defines what you want to accomplish. In our example, we'll tell Claude AI **sytem** role that is acting as a travel agent (used on my [ReisPlan](https://www.reisplan.net) site).\n\nFirst, we prepare the prompt statement:\n\n```PHP\n  // Prompt for the conversation\n    $messages = [\n        [\n            'role' =\u003e 'user',\n            'content' =\u003e 'You are a travel advisor that will deliver a detailed itinerary based on the information provided by the user.'\n        ]\n    ];\n```\n\nNext, we build a JSON array. In the below scenario, I'm only sending the prompt and the model using an **array** and then encoding it into JSON data using the **json_encode** function.\n\n```PHP\n// Convert messages to JSON\n  $data = [\n      'model' =\u003e 'claude-instant-1.2',\n      'max_tokens' =\u003e 2048,\n      'messages' =\u003e $messages\n  ];\n\n$jsonData = json_encode($postData);\n```\n\nNext, we set up the headers using an **array** to send the request using the Authorization header with our API Key and JSON content type. The curl array will set up the headers using **post** and the content using the **$jsonData** we built above. \n\n```PHP\n// Setup the curl data\n  $curl = curl_init();\n\n  curl_setopt_array($curl, [\n      CURLOPT_URL =\u003e $url,\n      CURLOPT_RETURNTRANSFER =\u003e true,\n      CURLOPT_ENCODING =\u003e '',\n      CURLOPT_MAXREDIRS =\u003e 10,\n      CURLOPT_TIMEOUT =\u003e 0,\n      CURLOPT_FOLLOWLOCATION =\u003e true,\n      CURLOPT_HTTP_VERSION =\u003e CURL_HTTP_VERSION_1_1,\n      CURLOPT_CUSTOMREQUEST =\u003e 'POST',\n      CURLOPT_POSTFIELDS =\u003e $jsonData,\n      CURLOPT_HTTPHEADER =\u003e [\n          'x-api-key: ' . $apiKey,\n          'anthropic-version: 2023-06-01',\n          'content-type: application/json'\n      ],\n  ]);\n```\n\nThe **curl_exec** function will execute the above curl command\n\n```PHP\n$response = curl_exec($curl);\n```\n\nFinally, we'll close the curl execution\n\n```PHP\n// Execute curl\ncurl_close($curl);\n```\n\n# Receiving the response\n\nWe'll use the **json_decode** function to read the $response variable from Claude AI.\n\n```PHP\n// Decode the API response\n$responseData = json_decode($response, true);\n```\nYou will receive a JSON response like this in the **$data** variable (don't copy this):\n\n```JSON\n{\n  \"id\": \"string\",\n  \"content\": [\n    {\n      \"text\": \"string\"\n    },\n    {\n      \"id\": \"string\",\n      \"name\": \"string\",\n      \"input\": {}\n    }\n  ],\n  \"model\": \"string\",\n  \"stop_reason\": \"end_turn\",\n  \"stop_sequence\": \"string\",\n  \"usage\": {\n    \"input_tokens\": 0,\n    \"output_tokens\": 0\n  }\n}\n```\n\n* content[0] is the first response\n* text is the response you're looking for\n\nNext, we'll extract the **$responseData** using the above and then explode individual lines in the response. The **$content** variable contains the whole response.\n\nBut, I used **$lines** to break the reply response so I could get multiple lines of data and have them displayed on the website.\n\n```PHP\n// Extract the assistant's reply\n$content = $responseData['content'][0]['text'];\n\n// Output the reply\n// Assuming $reply contains the response from the API\n$lines = explode(\"\\n\", $content);\n```\n\nThe following loop examines each **$line** received and displays it on the website using the echo function.\n\n```PHP\n// Loop through the lines\nforeach ($lines as $line) {\n    // Process each line as needed\n    if (preg_match('/^\\*\\*Day \\d+:\\*\\*$/', $line)) {\n        echo '\u003cstrong\u003e' . $line . \"\u003c/strong\u003e\u003cbr\u003e\";\n    } else {\n        echo $line . '\u003cbr\u003e';\n    }\n}\n```\n\n\n# Everything together\n\nNow, put it together in all its glory:\n\n```PHP\n$url = 'https://api.anthropic.com/v1/messages';\n\n// Your OpenAI API key\n$apiKey = '[API KEY]'; \n\n// Claude\n$model = 'claude-instant-1.2';\n$maxTokens = 2048;\n$temperature = 0.6;    \n$messages = [\n    [\n        'role' =\u003e 'system',\n        'content' =\u003e 'You are a travel advisor that will deliver a detailed itinerary based on the information provided by the user during the '.$season.' season. I am traveling to Denver, CO.'\n    ]\n];\n\n$data = [\n    'model' =\u003e $model,\n    'max_tokens' =\u003e $maxTokens,\n    'temperature' =\u003e $temperature,\n    'messages' =\u003e $messages\n];\n\n$jsonData = json_encode($data);\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, [\n    CURLOPT_URL =\u003e $url,\n    CURLOPT_RETURNTRANSFER =\u003e true,\n    CURLOPT_ENCODING =\u003e '',\n    CURLOPT_MAXREDIRS =\u003e 10,\n    CURLOPT_TIMEOUT =\u003e 0,\n    CURLOPT_FOLLOWLOCATION =\u003e true,\n    CURLOPT_HTTP_VERSION =\u003e CURL_HTTP_VERSION_1_1,\n    CURLOPT_CUSTOMREQUEST =\u003e 'POST',\n    CURLOPT_POSTFIELDS =\u003e $jsonData,\n    CURLOPT_HTTPHEADER =\u003e [\n        'x-api-key: ' . $apiKey,\n        'anthropic-version: 2023-06-01',\n        'content-type: application/json'\n    ],\n]);\n\n$response = curl_exec($curl);\n\ncurl_close($curl);\n\n$responseData = json_decode($response, true);\n\n$content = $responseData['content'][0]['text'];\n```\n\n\u003e Sure, I can recommend you check out Livin the Dream brewery in Littleton and Denver Beer Co in Englewood.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frkrehn%2Fclaudephp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frkrehn%2Fclaudephp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frkrehn%2Fclaudephp/lists"}