简体   繁体   中英

How do I return an error response from a XMLRPC server method in PHP?

If I use xmlrpc_server_call_method() in PHP, the resulting XML is generated for me. It works fine for regular responses, but let's say my method doesn't succeed (eg. post creation), how do I send a valid error response, like an error code?

Example:

function make_post($input) {
    
    // try to do a thing …
    
    if($post_created == true) {
        return $post_id;
    } else {
        // how do I trigger an actual error response?
        return false; // ?
    }
}

// set up a server
$server = xmlrpc_server_create();
xmlrpc_server_register_method($server, 'metaWeblog.newPost', 'make_post');

// fake a request
$request = xmlrpc_encode_request("metaWeblog.newPost", null, array('encoding' => 'utf-8'));

// call make_post()
$response = xmlrpc_server_call_method($server, $request, null, [
    'encoding' => 'utf-8'
]);

var_dump($response);

Output:

<?xml version="1.0" encoding="utf-8"?>
<methodResponse>
<params>
 <param>
  <value>
   <boolean>0</boolean>
  </value>
 </param>
</params>
</methodResponse>

Expected: (or similar)

<?xml version="1.0" encoding="utf-8"?>
<methodResponse>
    <fault>
        <value>
            <struct>
                <member>
                    <name>faultCode</name>
                    <value><int>4</int></value>
                </member>
                <member>
                    <name>faultString</name>
                    <value><string>Too many parameters.</string></value>
                </member>
            </struct>
        </value>
    </fault>
</methodResponse>

Instead of false return array('faultCode' => 666, 'faultString' => 'DOH!') to have an xmlrpc fault response (with your own code and string naturally, 666 and 'DOH:' are just exemplary):

function make_post($input) {    
    // ...    
    if ($post_created) {
        return $post_id;
    }

    return array('faultCode' => 666, 'faultString' => 'DOH!');
}

You can verify such an array value as well with xmlrpc_is_fault(php) and that manual page also gives more description about that array:

Fault description is available in $arg["faultString"] , fault code is in $arg["faultCode"] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM