Creating a MARC record from scratch in PHP using File_MARC
Posted on Fri 04 March 2011 in Libraries
In the past couple of days, two people have written me email essentially saying: "Dan, this File_MARC library sounds great - but I can't figure out how to create a record from scratch with it! Can you please help me?"
Yes, when you're dealing with MARC, you'll quickly get all weepy and get help from anyone you can. So, first things first - there is a really basic example that you can find in the File_MARC tests directory called marc_record_001.phpt. What, you couldn't find that? I'm not surprised, to be honest. Tests are great but when you install PEAR libraries the tests get separated from the code and you might not even know that there _are_ tests to cadge code from.
So instead, here's a whack of code that should provide a good starter for you:
<?phprequire 'File/MARC.php';$marc = new File_MARC_Record();$marc->appendField(new File_MARC_Data_Field('100', array( new File_MARC_Subfield('a', 'Doe, John'), ), null, null));$marc->appendField(new File_MARC_Data_Field('245', array( new File_MARC_Subfield('a', 'Main title: '), new File_MARC_Subfield('b', 'subtitle'), new File_MARC_Subfield('c', 'author') ), null, null));print "Yes, we do pretty print\n";print $marc . "\n";print "Yes, we write MARC21";$fh = fopen('marcy.mrc', 'w');fwrite($fh, $marc->toRaw());fclose($fh);print "... written.\n\n";print "Yes, we write MARCXML\n";print $marc->toXML() . "\n\n";print "Yes, we write MARC-in-JSON\n";print $marc->toJSON() . "\n\n";print "Yes, we even write the MARC-HASH JSON serialization\n";print $marc->toJSONHash() . "\n\n";?>
and here's the not very exciting output...
bash$ $ php marcy.php Yes, we do pretty printLDR 100 _aDoe, John245 _aMain title: _bsubtitle _cauthorYes, we write MARC21... written.Yes, we write MARCXML<?xml version="1.0" encoding="UTF-8"?><collection xmlns="http://www.loc.gov/MARC21/slim"> <record> <leader>00099na 2200049 4500 <datafield tag="100" ind1=" " ind2=" "> <subfield code="a">Doe, John </datafield> <datafield tag="245" ind1=" " ind2=" "> <subfield code="a">Main title: <subfield code="b">subtitle <subfield code="c">author </datafield> </record></collection>Yes, we write MARC-in-JSON{"leader":"00099 2200049 4500","fields":[ {"100":{"ind1":" ","ind2":" ","subfields":[ {"a":"Doe, John"}]}}, {"245":{"ind1":" ","ind2":" ","subfields":[ {"a":"Main title: "}, {"b":"subtitle"}, {"c":"author"}]}}]}Yes, we even write the MARC-HASH JSON serialization{"type":"marc-hash","version":[1,0],"leader":"00099 2200049 4500", "fields":[ ["100"," "," ",[["a","Doe, John"]]], ["245"," "," ",[["a","Main title: "],["b","subtitle"],["c","author"]]]]}
Hopefully this helps. Have at it!