Search code examples
phplaravelxpathsimplexml

SimpleXML get element content with xpath


I'm trying to return the values of elements of an XML that I receive from the database

the XML in the database looks like this

<?xml version="1.0" encoding="UTF-8"?>
<record
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"
    xmlns="http://www.loc.gov/MARC21/slim">

  <leader>00524nam a2200145Ia 4500</leader>
  <controlfield tag="001">25</controlfield>
  <controlfield tag="008">200930s9999  xx      000 0 und d</controlfield>
  <datafield tag="090" ind1=" " ind2=" ">
    <subfield code="a">25</subfield>
  </datafield>
  <datafield tag="100" ind1=" " ind2=" ">
    <subfield code="a">20220914              frey50        </subfield>
  </datafield>
  <datafield tag="101" ind1=" " ind2=" ">
    <subfield code="a">fre</subfield>
  </datafield>
  <datafield tag="200" ind1=" " ind2=" ">
    <subfield code="a">Etude sur les métiers -emplois de l'environnement pour la promotion de l'emploi environnemental comme appui a l'INDH</subfield>
    <subfield code="e">synthèse du rapport principal</subfield>
  </datafield>
  <datafield tag="210" ind1=" " ind2=" ">
    <subfield code="c">DES MINES ,DE L'EAU ET DE L'ENVIRONNEMENT</subfield>
  </datafield>
  <datafield tag="215" ind1=" " ind2=" ">
    <subfield code="a">33 p.</subfield>
  </datafield>
  <datafield tag="610" ind1=" " ind2=" ">
    <subfield code="a">ACTEURS;ENVIRENNEMENT;EMPLOI</subfield>
  </datafield>
  <datafield tag="676" ind1=" " ind2=" ">
    <subfield code="a">331.34</subfield>
  </datafield>
</record>

to get the datafield with tag "200" and its subfield with code "a"

$xml_string = simplexml_load_string($notices->biblio->metadata[0]->metadata);

$nodes = $xml_string->xpath('//datafield[@tag="200"]/subfield[@code="a"]/text()');

I tested the XPATH reeformatter.com and it works perfectly, but when I try to return the nodes I get an empty array. I tried to remove text() but unfortunately it didn't work as well, i tried all possibilities and nothing worked.


Solution

  • Your are probably better off confronting the namespaces in your xml head on:

    $xml_string->registerXPathNamespace("xxx", "http://www.loc.gov/MARC21/slim");
    $node = $xml_string->xpath('//xxx:datafield[@tag="200"]/xxx:subfield[@code="a"]/text()')[0];
    echo $node;
    

    Output:

    Etude sur les métiers -emplois de l'environnement pour la promotion de l'emploi environnemental comme appui a l'INDH