Home > database >  xml read field by name
xml read field by name

Time:12-10

Hi i must read a xml file, in a part of the code there are some field label with a name as reported in the example

       <Fields>
        <Field Name="JobId"><![CDATA[7096c681-3165-4137-95a3-4ae873af2132]]></Field>
        <Field Name="isDeleted"><![CDATA[0]]></Field>
        <Field Name="TopicId"><![CDATA[5870811]]></Field>
        <Field Name="Type"><![CDATA[Document]]></Field>
        <Field Name="CustomerId"><![CDATA[8063]]></Field>
        <Field Name="DocumentType"><![CDATA[volopress_pdf]]></Field>
        <Field Name="Inserted"><![CDATA[2021-01-02 08:47:51]]></Field>
        <Field Name="pageNumber"><![CDATA[17]]></Field>
        <Field Name="Position"><![CDATA[1]]></Field>
        <Field Name="TAG_Source"><![CDATA[Cronache di Napoli]]></Field>
        <Field Name="link_pdf"><![CDATA[http://www.pippo.com]]></Field>
        <Field Name="TAG_Topic"><![CDATA[Terremoti]]></Field>
        <Field Name="isValidSnippet"><![CDATA[True]]></Field>
      </Fields>

I want to read only the field with the name "link_pdf"

If i use this code

$alink = $rassegna->Fields->Field[23];

I can read the value, but in some case this isn't a good work, how i can access to the value by the name of field?

$alink = $rassegna->Fields->Field['link_export'];

not work

CodePudding user response:

Use XPath to select the Field and apply a predicate restricting to the one(s) that have a Name attribute value of "link_export":

$xml = new SimpleXMLElement($string);
$result = $xml->xpath('/Fields/Field[@Name="link_export"]');
while(list( , $node) = each($result)) {
  echo '/Fields/Field[@Name="link_export"]: ',$node,"\n";
}

CodePudding user response:

thanks for the answer but don't work

<?php

$xml=simplexml_load_file("02012021.xml") or die("Error: Cannot create object");

foreach($xml->Reports->Report[1]->Hits[0]->children() as $rassegna) {
        echo $rassegna->Order . "<br>";
        echo $rassegna->DocumentReference . "<br>";
        echo $rassegna->Title . "<br>";
        echo $rassegna->Content . "<br>";
        //$alink = $rassegna->Fields->Field['link_export'];
        //$alink = $rassegna->Fields->Field[23];
        $xml1 = new SimpleXMLElement($string);
        $result = $xml1->xpath($rassegna . '/Fields/Field[@Name="link_export"]');
        while(list( , $node) = each($result)) {
         echo '/Fields/Field[@Name="link_export"]: ',$node,"\n";
        }
        echo $alink . "<br>";
        echo "<a href='". $alink . "'> link </a>";
        echo "<br/><br/>";
}
?>

where is the error? The complete struct of the xml file are on http://web.ct.ingv.it/xml/02012021.xml in another word are Reports->Report->Hits->Fields->Field

  • Related