将PHP中的XML解析为变量

时间:2017-08-31 03:38:20

标签: php xml

我制作了一个需要接收以下XML的PHP​​脚本:

<contact_email>people@example.com</contact_email>
<contact_password>hash_in_sha256</contact_password>

我通常用JSON做事,但在这个项目中我需要使用XML。因此,要在PHP中解析JSON对象,请使用以下代码和以下JSON:

{
    "contact_email":"people@example.com",
    "contact_password":"hash_in_sha256"
}

剧本:

$jsonBody = file_get_contents("php://input");
$jsonBody = json_decode($jsonBody);

$contact_email = $jsonBody->contact_email;
$contact_password = $jsonBody->contact_password;

但是我应该怎样做才能将XML中的“people@example.com”和“hash_in_sha256”作为PHP中的变量?

1 个答案:

答案 0 :(得分:0)

就像Sahil Gulati所说,使用NSString *service = @"https://speech.googleapis.com/v1/speech:recognize"; service = [service stringByAppendingString:@"?key="]; service = [service stringByAppendingString:API_KEY]; NSData *audioData = [NSData dataWithContentsOfFile:[self soundFilePath]]; NSDictionary *configRequest = @{@"encoding":@"LINEAR16", @"sampleRateHertz":@(SAMPLE_RATE), @"languageCode":@"en-US", @"maxAlternatives":@30}; NSDictionary *audioRequest = @{@"content":[audioData base64EncodedStringWithOptions:0]}; NSDictionary *requestDictionary = @{@"config":configRequest, @"audio":audioRequest}; NSError *error; NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:& error]; NSString *path = service; NSURL *URL = [NSURL URLWithString:path]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; // if your API key has a bundle ID restriction, specify the bundle ID like this: [request addValue:[[NSBundle mainBundle] bundleIdentifier] forHTTPHeaderField:@"X-Ios-Bundle-Identifier"]; NSString *contentType = @"application/json"; [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:requestData]; [request setHTTPMethod:@"POST"]; NSLog(@"RESULT: %@", request.description); NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ NSString *stringResult = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; _textView.text = stringResult; NSLog(@"RESULT: %@", stringResult); }); }]; [task resume]; ,只要确保你有有效的xml,应该只有一个顶级节点,例如:

func transcribeFile(url: URL) {
    var audioData: Data?
    do {
        audioData = try Data(contentsOf: url)
    } catch {
        print("couldn't transcribe")
    }
    if audioData == nil {
        return
    }
    sendRequestRequest(audioData: audioData!)


}

func sendRequestRequest(audioData: Data) {
    /**
     Request
     post https://speech.googleapis.com/v1/speech:recognize
     */

    // Add Headers
    let headers = [
        "X-Ios-Bundle-Identifier": Bundle.main.bundleIdentifier!,
        "Content-Type":"application/json",
        ]

    // JSON Body
    let body: [String : Any] = [
        "audio": [
            "content": audioData.base64EncodedString()
        ],
        "config": [
            "encoding": "LINEAR16",
            "sampleRateHertz": 16000,
            "languageCode": "en-US",
            "maxAlternatives": 30
        ]
    ]

    // Fetch Request
    Alamofire.request("https://speech.googleapis.com/v1/speech:recognize?key=APIKEY", method: .post, parameters: body, encoding: JSONEncoding.default, headers: headers)
        .validate(statusCode: 200..<300)
        .responseJSON { response in
            if (response.result.error == nil) {
                debugPrint("HTTP Response Body: \(response.data)")
            }
            else {
                debugPrint("HTTP Request failed: \(response.result.error)")
            }
    }
}