How can I convert this Ruby Gem to PHP?

token = "your_nypl_api_token"
client = NyplRepo::Client.new(token)
```
```
token = "your_nypl_api_token"
options = {:debug => true, :server_url => "http://api.repo.nypl.org/api/v1"}
client = client = NyplRepo::Client.new(token, options)

Also

url = "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.xml"
    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)

    headers = { "Authorization" => "Token token=XXXXXX" }
    request = Net::HTTP::Get.new(uri.request_uri, headers)
    response = http.request(request)
    @response = response.body

@response = response.body

Regards

Use cURL.

$token = 'your_nypl_api_token';
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, 'http://api.repo.nypl.org/api/v1/items?identifier_type=local_bnumber&identifier_val=b########');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Authorization: Token',
    "Token: $token"
));
$resp = curl_exec($curl);
curl_close($curl);

echo $resp;

You can get more info about the API your using at this Link

commented: +1 +13

Also i get a prompt for username and password, how can I handle it automatically?

Upon doing some tests myself, it doesn't appear as though the NYPL.org api is designed for cURL calls from PHP because the token being submitted within a header request in this method doesn't appear to work. Have you tried asking support at api.repo.nypl.org if they accept this method?

I already sent a message. I'm expecting a reply.

Try to change the header to:

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    "Authorization: Token token=$token"
));

Then it should work fine. To debug the request add:

curl_setopt($curl, CURLINFO_HEADER_OUT, true);

And:

$info = curl_getinfo($curl, CURLINFO_HEADER_OUT);

Which prints:

GET /api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json HTTP/1.1
Host: api.repo.nypl.org
Accept: */*
Authorization: Token token=YOUR_TOKEN

It looks ok now expect that though i see the content i'm not able to use file_get_contents to serialize and get the file contents

Thanks for your help.

Hi,

you don't need file_get_contents() in this case, if you get the results in XML format then use simplexml_load_string(), like this:

$xml = simplexml_load_string($resp);

It returns an object, for example:

echo $xml->response->capture[0]->itemLink;

If instead you get the results as JSON use json_decode():

$data = json_decode($resp, true);

By adding true as second argument, $data will be a simple array, otherwise it will be an object.

Docs:

You are the hero.

It works. Thanks so much.

Please too. in xml, instead content_partner, it appears as content-partner.

I find it difficult to output that.

SimpleXML should not replace the underscore with an hyphen, probably the XML generated by the NYPL has already that format. Could you provide the query link? In any case, when this happens use the alternative syntax to call the variables:

$a = 'hello';

echo $a;
echo ${'a'}; # alternative syntax

So, for example, with the XML object you would write:

echo $xml->response->{'content-partner'}->title;

Reference: http://php.net/manual/en/simplexml.examples-basic.php#example-5913

Thanks so much.

It works.

To define different formats you have to append the parameter httpAccept to the link, for example:

&httpAccept=application/json
&httpAccept=application/xml
&httpAccept=application/atom+xml
&httpAccept=application/rss+xml

Documentation: http://www.nature.com/developers/documentation/api-references/opensearch-api/#apiref

So to get the document in XML format you would write:

$url = 'http://api.nature.com/content/opensearch/request?queryType=searchTerms&query=darwin&httpAccept=application/xml';

Accessing the information is not simple, here I will explain three methods with, from the hardest to the easiest:

  • xml
  • json
  • json (as array)
XML

When using the XML method you have to check the source to read the namespaces used to define the document. With SimpleXML you can get the list by using this method getDocNamespaces():

$content = simplexml_load_file($url);
print_r($content->getDocNamespaces(true, true));

Which returns:

Array
(
    [xsi] => http://www.w3.org/2001/XMLSchema-instance
    [srw] => http://docs.oasis-open.org/ns/search-ws/sru-2-0-response
    [] => http://docs.oasis-open.org/ns/search-ws/sru-2-0-response
    [ns1] => http://docs.oasis-open.org/ns/search-ws/sru-2-0-response
    [dc] => http://purl.org/dc/elements/1.1/
    [dcterms] => http://purl.org/dc/terms/
    [pam] => http://prismstandard.org/namespaces/pam/2.0/
    [prism] => http://prismstandard.org/namespaces/basic/2.1/
    [xhtml] => http://www.w3.org/1999/xhtml
    [ns2] => http://docs.oasis-open.org/ns/search-ws/sru-2-0-response
    [ns3] => http://docs.oasis-open.org/ns/search-ws/sru-2-0-response
    [ns4] => http://www.nature.com/opensearch/ns/sru/
)

If you read the document structure you will see:

<records>
    <record>
        <recordData>
            <pam:message
                xmlns:dc="http://purl.org/dc/elements/1.1/"
                xmlns:dcterms="http://purl.org/dc/terms/"
                xmlns:pam="http://prismstandard.org/namespaces/pam/2.0/"
                xmlns:prism="http://prismstandard.org/namespaces/basic/2.1/"
                xmlns:xhtml="http://www.w3.org/1999/xhtml"
                xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
                xsi:schemaLocation="http://prismstandard.org/namespaces/pam/2.0/ http://prismstandard.org/schemas/pam/2.1/pam.xsd">

                <pam:article>
                    <xhtml:head>
                        <dc:identifier>doi:10.1038/081007a0</dc:identifier>
                        <dc:title>&lt;i&gt;The &lt;span&gt;Darwin&lt;/span&gt; Celebrations at Cambridge&lt;/i&gt;</dc:title>
                        ...
                        <prism:publicationDate>1909-07-01</prism:publicationDate>
                        ...

So to access the information under the object recordData you have to load the namespaces for:

  • pam:
  • xhtml:
  • dc: & prism:

Basically to get the first record you have to do this:

# loading the content, no need of file_get_contents
$content = simplexml_load_file($url);

# loading the pam namespace
$pam    = $content->records->record[0]->recordData->children('http://prismstandard.org/namespaces/pam/2.0/');

# loading the xhtml namespace
$xhtml  = $pam->message->article->children('http://www.w3.org/1999/xhtml');

# loading the dc namespace
$dc     = $xhtml->head->children('http://purl.org/dc/elements/1.1/');

# loading the prism namespace
$prism  = $xhtml->head->children('http://prismstandard.org/namespaces/basic/2.1/');

print_r($dc);
print_r($prism);

Which returns:

# dc objects
SimpleXMLElement Object
(
    [identifier] => doi:10.1038/081007a0
    [title] => <i>The <span>Darwin</span> Celebrations at Cambridge</i>
    [publisher] => Nature Publishing Group
    [description] => <p>A GENERAL account of the proceedings of the Darwin celebrations at Cambridge on June 22–24, and a list of distinguished delegates and other representatives of science who came from the four corners of the earth to proclaim the greatness of Charles Darwin and his work, was given in last week's NATURE. As the chief speeches were delivered on the day we went to press, and on Thursday last, we were prevented from including any report of them in the article, which, however, we are now able to supplement. Short speeches were made in the Senate House on June 23, when the delegates were received by the Chancellor, Lord Rayleigh, and the addresses were presented; and also at the banquet given in the evening of that day.</p>
)

# prism objects
SimpleXMLElement Object
(
    [productCode] => nature
    [publicationName] => Nature
    [doi] => 10.1038/081007a0
    [publicationDate] => 1909-07-01
    [volume] => 81
    [number] => 2070
    [startingPage] => 7
    [endingPage] => 14
    [url] => http://dx.doi.org/10.1038/081007a0
    [genre] => Research
    [copyright] => © 1909 Nature Publishing Group
)
JSON

By using JSON you don't have to load the namespaces. For example:

$url = 'http://api.nature.com/content/opensearch/request?queryType=searchTerms&query=darwin&httpAccept=application/json';
$content = json_decode(file_get_contents($url));

The variable $content will return some objects that will be accessible through the alternative syntax for the variable names:

print_r($content->feed->entry[0]->{'sru:recordData'}->{'pam:message'}->{'pam:article'}->{'xhtml:head'});

This will return the same information returned by the XML example:

stdClass Object
(
    [dc:identifier] => doi:10.1038/081007a0
    [dc:title] => <i>The <span>Darwin</span> Celebrations at Cambridge</i>
    [prism:productCode] => nature
    [dc:creator] => 
    [prism:publicationName] => Nature
    [prism:issn] => 
    [prism:eIssn] => 
    [prism:doi] => 10.1038/081007a0
    [dc:publisher] => Nature Publishing Group
    [dc:description] => <p>A GENERAL account of the proceedings of the Darwin celebrations at Cambridge on June 22–24, and a list of distinguished delegates and other representatives of science who came from the four corners of the earth to proclaim the greatness of Charles Darwin and his work, was given in last week's NATURE. As the chief speeches were delivered on the day we went to press, and on Thursday last, we were prevented from including any report of them in the article, which, however, we are now able to supplement. Short speeches were made in the Senate House on June 23, when the delegates were received by the Chancellor, Lord Rayleigh, and the addresses were presented; and also at the banquet given in the evening of that day.</p>
    [prism:publicationDate] => 1909-07-01
    [prism:coverDate] => 
    [prism:aggregationType] => 
    [prism:volume] => 81
    [prism:number] => 2070
    [prism:startingPage] => 7
    [prism:endingPage] => 14
    [prism:url] => http://dx.doi.org/10.1038/081007a0
    [prism:channel] => 
    [prism:section] => 
    [dc:subject] => 
    [prism:genre] => Research
    [prism:copyright] => © 1909 Nature Publishing Group
)
JSON (as array)

The last method requires a simple change to the json_decode() function, by adding the second argument as boolean TRUE the object will be converted to a simple array, so:

$content = json_decode(file_get_contents($url), TRUE);
print_r($content['feed']['entry'][0]['sru:recordData']['pam:message']['pam:article']['xhtml:head']);

Hope is this what you were asking for.

This was exactly what i wanted. So grateful.

I tried implementing scribd which worked fine except that it doesnt give me the exact search like when using their front end search.

Below is my code:

    $result = simplexml_load_file("http://api.scribd.com/api?method=docs.search&api_key=$scribd_api_key&num_start=0&num_results=100&query=$barcode&my_user_id=33616452&scope=all&simple=false");
    //echo $result->result_set->result[0]->title;
     $totalResultsAvailable = $result->result_set[totalResultsAvailable];
     $totresultsreturned = $result->result_set[totalResultsReturned];
    // echo "<tr><td>&nbsp;</td><td>No of results: $totalResultsAvailable </td></tr>";
    foreach ($result->result_set->result as $rsinfo):
        $doc_id=$rsinfo->doc_id;
        $access_key=$rsinfo->access_key;
        $title=$rsinfo->title;
        $description=$rsinfo->description;
        $tags=$rsinfo->tags;
        $license=$rsinfo->license;
        $thumbnail_url=$rsinfo->thumbnail_url;
        $page_count=$rsinfo->page_count;
        $download_formats=$rsinfo->download_formats;
        $reads=$rsinfo->reads;
        $uploaded_by=$rsinfo->uploaded_by;
        $uploader_id=$rsinfo->uploader_id;
        $when_uploaded=$rsinfo->when_uploaded;
        $when_updated=$rsinfo->when_updated;
        $block_count=$rsinfo->block_count;
endforeach;

I've registered an account and got your same result, probably their system requires some time (few hours) to enable the API key.

If by waiting you don't solve try to ask their support team: api-support@authorSTREAM.com

In general, for generic issues like these try to get a response from the support teams before asking to Daniweb forums, here we help in specific programming issues.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.