PHP SOAP 答案的效用函数

PHP utility function for SOAP answer

我有一个 SOAP 响应,如下所示

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetShowInformationResponse xmlns="http://www.xxxx.com/xxxxWS/">
      <GetShowInformationResult>
        <CustomFields>
          <CustomField>
            <Name>string</Name>
            <Value>string</Value>
          </CustomField>
          <CustomField>
            <Name>string</Name>
            <Value>string</Value>
          </CustomField>
        </CustomFields>
      </GetShowInformationResult>
    </GetShowInformationResponse>
  </soap:Body>
</soap:Envelope>

我的 SOAP 调用给了我一个自定义字段列表:

$result->GetShowInformationResult->CustomFields->CustomField

它的回答是这样的(尽管可能是对象或 null):

Array ( [0] => stdClass Object ( [Name] => YouTubeID [Value] => XPCHmIOml0f ) [1] => stdClass Object ( [Name] => Episode Title [Value] => Raw Foods ) )

我需要编写一个实用函数,根据 'name' 提取我想要的字段,然后给我 'value'。这是我目前拥有的,但无法正常工作...

function ExtractCustomField($fieldName, $customFields) {
 // $customFields might be an object, null, or an array.
  $parsed = array();
  if (is_array($customFields) == false && $customFields != null) {
   $parsed = array($customFields);
  } elseif (is_array($customFields)) {
   $parsed = $customFields;
  }

  // loop through the fields and find the one we are looking for
  $returnValue = null;
  foreach($field as $customFields) {
   if ($field->Name == $fieldName) {
    $returnValue = $field->Value;
    break;
   }
  }

  return $returnValue;
}

ExtractCustomField('YouTubeID','$result->GetShowInformationResult->CustomFields->CustomField');

我很笨,@hakre 帮我解决了。

问题是混淆了 foreach 中的变量,并且没有 echo 函数。还发现如果它返回一个对象我没有把它正确地放入数组中。

function ExtractCustomField($fieldName, $customFields) {
// $customFields might be an object, null, or an array.
 if($customFields == null) {
   $customFields = array();       
 } else {
   $customFields = is_array($customFields) ? $customFields : array($customFields);
 }

  // loop through the fields and find the one we are looking for
  $returnValue = null;
  foreach($customFields as $field) {
   if ($field->Name == $fieldName) {
    $returnValue = $field->Value;
    break;
   }
  }

  return $returnValue;
}

echo ExtractCustomField('YouTubeID',$result->GetShowInformationResult->CustomFields->CustomField);