3

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.)

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

Based on the structure of your XML, it might be easier to just loop over the <str> elements and build up an array mapping the name attribute to the content.

$dat = simplexml_load_string($xml);

$attributes = [];

foreach ($dat->str as $str) { 
  $attributes[(string) $str['name']] = (string) $str;
}

You could then access the "title" element under $attributes['title'] (or assign it to your $ergTitle variable, etc).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.