Search code examples
phpxmlsimplexml

PHP simpleXML: parse specific attribute value of multiple entries


I have the following XML:

<doc>
    <str name="segment">20170913064727</str>
    <str name="digest">427522d5ceb605f87755c909deac698a</str>
    <str name="title">AMS Site</str>
<doc>

I want to parse it and to save the value of "title" to the variable $ergTitle (that would be "AMS Site").

I have the following PHP code:

foreach($data->result->doc as $dat) {
    foreach ($dat->str as $att) {
        foreach ($att->attributes() as $a => $b) {
            echo $a,'="',$b,"\"\n" . '<br>';
            if ($b=='title') {
                echo "OK";
            }
        }
    }
}

Which results to:

name="segment" 
name="digest" 
name="id" 
name="title" 
OKname="url" 
name="content" 

But how can I now get the value of name="title" and save it to my variable?

Goal: I want to print the content of "content", "url", "title" and so on (its for a result site of a search query.)


Solution

  • You're iterating over the element's attributes. In your loop, the element value is in the $dat variable. In this example, I had to remove one foreach() loop because of the sample XML:

    <?php
    $data = simplexml_load_file("a.xml");
    foreach($data->str as $dat) {
        foreach ($dat->attributes() as $a => $b) {
            echo $a,'="',$b,'"';
            if ($b=='title') {
                echo "right one";
            }
        }
        echo " -> ".$dat."<br>";
    }
    
    /* result */
    name="segment" -> 20170913064727
    name="digest" -> 427522d5ceb605f87755c909deac698a
    name="title" right one -> AMS Site
    

    If you want to put the title when you find it in a variable, use the same variable inside the loop:

    <?php
    $data = simplexml_load_file("a.xml");
    foreach($data->str as $dat) {
        foreach ($dat->attributes() as $a => $b) {
            if ($b=='title') {
                $title = $dat;
                break;
            }
        }
    }
    echo "Title: ".$dat; // Title: AMS Site