用于 SOAP 答案的 PHP 实用程序函数


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

它的回答是这样的(虽然可能是对象或空):

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

我需要编写一个实用程序函数,该函数根据"名称"提取我想要的字段,然后给我"值"。这是我到目前为止所拥有的,但无法让它工作......

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);