xml read field by name

Viewed 65

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

3 Answers

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";
}

You can find that items by one xpath, don't follow all the structure of source xml

$xml = simplexml_load_file('02012021.xml');
$result = $xml->xpath('//Field[@Name="link_pdf"]');
foreach($result as $node) {
    echo "$node<br>\n";
}

Unfortunately I have to follow the whole structure, because in addition to that record I have to read others

<?php

$xml=simplexml_load_file("02012021.xml") or die("Error: Cannot create object");
$i=0;
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 = $xml->xpath('//Field[@Name="link_export"]');
        echo $alink[$i] . "<br>";
        echo "<a href='". $alink[$i] . "'> link </a>";
        echo "<br/><br/>";
        $i=$i+1;
}
?>

I solved it with the solution just posted

Related