Search code examples
phpsimplexml

SimpleXML Node Selection


I am trying to select a line in an XML using SimpleXML in PHP. I have toe code loading in the XML which looks like this.

    <Row>
        <Cell name="ID">S061102000000000000000006492017092915:13</Cell>
    </Row>

I have got my code to select the name however want it to select the value for that name. At the moment my line in PHP looks like this

    <?php
       $xml=simplexml_load_file("test.xml") or die("Error: Cannot create 
       object");

       echo "'".$xml->book[0]->title['name'] . "',<br>";
     ?>

So this obviously outputs the text

ID

I however want the value for this row. Just so you are also aware there are more Cell Name values where I want to get the content from such as

<Cell name="Name">First Name</Cell>

Solution

  • Using your xml format, the code should look something like this

    $xml = '<Row>
        <Cell name="ID">S061102000000000000000006492017092915:13</Cell>
    </Row>';
    
    $data = new SimpleXMLElement($xml);
    echo "Name:" . $data->Cell["name"] . "\n";
    echo "Value:" . (string)$data->Cell . "\n";
    

    or if your have to handle multiple cell tags, loop over the data

    $xml = '<Row>
        <Cell name="ID">S061102000000000000000006492017092915:13</Cell>
        <Cell name="Name">Value</Cell>
    </Row>';
    
    $data = new SimpleXMLElement($xml);
    foreach ($data as $cell) {
        echo "Name:" . $cell["name"] . "\n";
        echo "Value:" . (string)$cell . "\n";
    }