2017-12-14 3 views
0

이 질문은이 스레드에서 대답으로 시장 :PHP cURL을 사용하여 XML 파일을 보내는 방법은 무엇입니까?

How to POST an XML file using cURL on php?

그러나 그것은 단지 컬 XML 코드를 전송하는 방법을 보여 이후 그 대답은 정말 내 생각에 올바른 답하지 않았다. XML 파일을 보내야합니다.

public Guid? UploadXmlFile() 
{ 
    var fileUploadClient = new WebClient(); 
    fileUploadClient.Headers.Add("Content-Type", "application/xml"); 
    fileUploadClient.Headers.Add("Authorization", "api " + ApiKey); 

    var rawResponse = fileUploadClient.UploadFile(Url, FilePath); 
    var stringResponse = Encoding.ASCII.GetString(rawResponse); 

    var jsonResponse = JObject.Parse(stringResponse); 
    if (jsonResponse != null) 
    { 
     var importFileId = jsonResponse.GetValue("ImportId"); 
     if (importFileId != null) 
     { 
      return new Guid(importFileId.ToString()); 
     } 
    } 
    return null; 
} 

나는 여러 가지 방법으로 시도하고이 내 최신 시도입니다 :

기본적으로,이 C# 코드는 PHP로 변환 할 이 필요합니다.

컬 전화 :

/** 
* CDON API Call 
* 
*/ 
function cdon_api($way, $method, $postfields=false, $contenttype=false) 
{ 
    global $api_key; 

    $contenttype = (!$contenttype) ? 'application/x-www-form-urlencoded' : $contenttype; 

    $curlOpts = array(
     CURLOPT_URL => 'https://admin.marketplace.cdon.com/api/'.$method, 
     CURLOPT_RETURNTRANSFER => TRUE, 
     CURLOPT_TIMEOUT => 60, 
     CURLOPT_HTTPHEADER => array('Authorization: api '.$api_key, 'Content-type: '.$contenttype, 'Accept: application/xml') 
    ); 

     if ($way == 'post') 
     { 
      $curlOpts[CURLOPT_POST] = TRUE; 
     } 
     elseif ($way == 'put') 
     { 
      $curlOpts[CURLOPT_PUT] = TRUE; 
     } 

     if ($postfields !== false) 
     { 
      $curlOpts[CURLOPT_POSTFIELDS] = $postfields; 
     } 

    # make the call 
    $ch = curl_init(); 
    curl_setopt_array($ch, $curlOpts); 
    $response = curl_exec($ch); 
    curl_close($ch); 

    return $response; 
} 

[파일 내보내기 :

/** 
* Export products 
* 
*/ 
function cdon_export() 
{ 
    global $api_key; 

    $upload_dir = wp_upload_dir(); 
    $filepath = $upload_dir['basedir'] . '/cdon-feed.xml'; 

    $response = cdon_api('post', 'importfile', array('uploaded_file' => '@/'.realpath($filepath).';type=text/xml'), 'multipart/form-data'); 

    echo '<br>Response 1: <pre>'.print_r(json_decode($response), true).'</pre><br>'; 

    $data = json_decode($response, true); 

     if (!empty($data['ImportId'])) 
     { 
      $response = cdon_api('put', 'importfile?importFileId='.$data['ImportId'], false, 'text/xml'); 

      echo 'Response 2: <pre>'.print_r(json_decode($response), true).'</pre><br>'; 

      $data = json_decode($response, true); 
     } 
} 

하지만 얻을 출력은 이것이다 :


응답 1 :

stdClass Object ( ) [메시지] = 요청에 유효한 미디어 유형이 없습니다. )


나는 다른 장소, application/xml, multipart/form-datatext/xml에서 다른 종류의 약을 실험,하지만 아무것도 작동하지 않습니다.

어떻게 작동 시키나요? cURL을 사용하여 XML 파일을 보내려면 어떻게해야합니까? 나에게

+1

는 PHP에서하지 않습니다 않는 C# 코드처럼 보이는 수동으로 "CURLOPT_POSTFIELDS : HTTP"POST "작업에 게시 할 전체 데이터 파일을 게시하려면 파일 이름 앞에 @를 붙이고 전체 경로를 사용하십시오." – RamRaider

+0

@RamRaider 예. 하지만 작동하지 않습니다. –

+0

@RamRaider @ 접근법은 몇 년 전에 비싸지지 않았고, 5.5에서 신뢰할 수 없게되었고, 5.6에서 훨씬 더 신뢰할 수 없게되었고, 7.0에서 완전히 작동을 멈추었습니다. @ – hanshenrik

답변

1

, 그냥

function UploadXmlFile(): ?string { 
    $ch = curl_init ($url); 
    curl_setopt_array ($ch, array (
      CURLOPT_POST => 1, 
      CURLOPT_HTTPHEADER => array (
        "Content-Type: application/xml", 
        "Authorization: api " . $ApiKey 
      ), 
      CURLOPT_POSTFIELDS => file_get_contents ($filepath), 
      CURLOPT_RETURNTRANSFER => true 
    )); 
    $jsonResponse = json_decode (($response = curl_exec ($ch))); 
    curl_close ($ch); 
    return $jsonResponse->importId ?? NULL; 
} 

그러나 적어도 1 차이에 해당하는, 당신의 PHP 코드가 헤더 'Accept: application/xml'을 추가하여 C# 코드는

+0

흠,'$ response'는 비어 있습니다 .json datas가 들어 있어야합니다 –

+0

트릭은 CURLOPT_POSTFIELD를 ** 문자열로 설정하는 것입니다. ** 그렇지 않으면 cURL이 Content-Type을 조사하지 않으므로 (올바른 'application/xml' Content-Type을 사용할 수 있습니다.) SOAP 클라이언트에 대해 동일한 작업을 몇 차례해야했습니다 예전에 이것은 큰 걸림돌이었습니다 – LSerni

+0

문자열로 추가했는데 이제는 요청에 유효한 멀티 파트 콘텐츠가 없습니다. –

관련 문제