falcs
falcs

Reputation: 509

Constructing a URL using $_POST in PHP

I am creating a page where users can submit metadata about content to a database by submitting the Digital Object Identifier (DOI) of the content. The site will then go and look up the metadata of content on www.crossref.org and present a summary of the data before adding it to the database

I have created a form for users to enter the DOI

<FORM ACTION="newref-getxml.php" METHOD=POST>
<P><strong>New Reference Form</strong><BR>
DOI: <INPUT NAME="send_doi"><BR>
<BR>
<INPUT TYPE=SUBMIT NAME="submitref" VALUE="SUBMIT">
</FORM>

And a file to fetch and read the XML (I have removed my API KEY from the URL for obvious reasons)

<?php
  echo $_POST[send_doi]; // check post data is coming though
  $xml = simplexml_load_file("http://www.crossref.org/openurl/id=doi:'$_POST[send_doi]'&noredirect=true&pid=APIKEY&format=unixref");
?>
<p>
   Title: <?php echo $xml->doi_record->crossref->journal->journal_article->titles->title;?><br />
   Year: <?php echo $xml->doi_record->crossref->journal->journal_article->publication_date->year;?><br />
   Journal: <?php echo $xml->doi_record->crossref->journal->journal_metadata->full_title;?><br />
   DOI: <?php echo $xml->doi_record->crossref->journal->journal_article->doi_data->doi;?>
</p>

The problem is with inserting the user submitted DOI into the URL, I thought I could just paste '$_POST[send_doi]' into the URL where the DOI should go, but that is not working.

All I get is

10.3998/3336451.0009.101 Title: Year: Journal: DOI:

When submitting a DOI

How you write the URL to include the '$_POST[send_doi]' value?

Upvotes: 0

Views: 594

Answers (2)

CodeAngry
CodeAngry

Reputation: 12985

simplexml_load_file("http://www.crossref.org/openurl/id".
    "?doi=".urlencode($_POST[send_doi]).
    "&noredirect=true&pid=APIKEY&format=unixref");

Added a question mark as I don't see it in your URL. A better alternative is http_build_query(). Check it out!

simplexml_load_file('http://www.crossref.org/openurl/id?'. // <- Question Mark here
    http_build_query(array(
        'doi'       => $_POST[send_doi],
        'noredirect'    => 'true',
        'pid'       => 'APIKEY',
        'format'    => 'unixref',
    ))
);

Upvotes: 2

phpisuber01
phpisuber01

Reputation: 7715

Try this:

$xml = simplexml_load_file("http://www.crossref.org/openurl/id=doi:'{$_POST['send_doi']}'&noredirect=true&pid=APIKEY&format=unixref");

Array keys of type string need to be encapsulated in single quotes. When including a variable into a string, use {} to enclose the variable itself.

Also, make sure you validate that input so you dont have erraneous calls going to that API. Regex works well. See: preg_match().

Upvotes: 0

Related Questions