要在 Swift 中调用 PHP,可以使用以下几种方法:
URLSession 发送 HTTP 请求,将 PHP 脚本的 URL 作为请求的目标地址。然后解析 PHP 脚本返回的数据。例如:let url = URL(string: "http://example.com/script.php")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Error: \(error)")
} else if let data = data {
let result = String(data: data, encoding: .utf8)
print("Result: \(result ?? "")")
}
}
task.resume()
import Alamofire
AF.request("http://example.com/script.php").responseString { response in
switch response.result {
case .success(let value):
print("Result: \(value)")
case .failure(let error):
print("Error: \(error)")
}
}
Process 类来运行 PHP 命令。例如:import Foundation
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/php")
process.arguments = ["-r", "echo 'Hello, World!';"]
let pipe = Pipe()
process.standardOutput = pipe
do {
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let result = String(data: data, encoding: .utf8) {
print("Result: \(result)")
}
} catch {
print("Error: \(error)")
}
需要注意的是,以上方法都是在 Swift 中调用远程或本地的 PHP 脚本,并获取返回的结果。如果需要在 PHP 中调用 Swift,可以考虑使用相关的框架和库,例如 Perfect、Vapor 等。
上一篇:php类名调用属性方法
下一篇:php获取不到月
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站