SPQRInc
SPQRInc

Reputation: 188

Can not get content of XML-child

I would like to get the content of this:

    <wp:postmeta>
        <wp:meta_key>_wp_attached_file</wp:meta_key>
        <wp:meta_value><![CDATA[/home/image.jpg]]></wp:meta_value>
    </wp:postmeta>

This is how I tried to solve this:

    $this->xml = simplexml_load_file($this->filepath);

    foreach($this->xml->channel->item as $item){

            $content = $item->children('http://purl.org/rss/1.0/modules/content/');
            $excerpt = $item->children('http://wordpress.org/export/1.2/excerpt/');
            $post = $item->children('http://wordpress.org/export/1.2/');

            foreach($post->postmeta as $meta){

                if($meta->meta_key == '_wp_attached_file'){
                    var_dump($meta->meta_value);
                }
                ($meta->meta_key == '_wp_attached_file') ? $path = $meta->meta_value : $path = null; 
            }
        }

But unfortunately I'm getting this result:

object(SimpleXMLElement)#816 (1) {
  [0]=>
  object(SimpleXMLElement)#820 (0) {
  }
}

This element seems to be empty? How can I get the value /home/image.jpg?

Upvotes: 0

Views: 655

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

Using var_dump on SimpleXMLElement can tend to give you partial results. There are a couple of ways of getting some useful output. With a very cut down version of the XML, this hopefully will give you an idea...

if($meta->meta_key == '_wp_attached_file'){
    var_dump($meta->meta_value);
    echo (string)$meta->meta_value.PHP_EOL;
    echo $meta->meta_value->asXML();
}

This outputs...

class SimpleXMLElement#9 (1) {
  public ${0} =>
  class SimpleXMLElement#11 (0) {
  }
}
/home/image.jpg
<wp:meta_value><![CDATA[/home/image.jpg]]></wp:meta_value>

You could simplify the code if you just wanted the <meta_value> elements of the _wp_attached_file by using XPath and extracting just this data...

$xml->registerXPathNamespace("wp", "http://wordpress.org/export/1.2/");
foreach($xml->item as $item){
    $attachedFile= $item->xpath("//wp:postmeta[wp:meta_key[text() = '_wp_attached_file']]/wp:meta_value");
    var_dump($attachedFile);
    echo (string)$attachedFile[0].PHP_EOL;
    echo $attachedFile[0]->asXML();
}

The XPath looks for the meta_key which is '_wp_attached_file' and then gets the meta_value element. As you have the wp namespace, this has to be registered with the xml before using it in any XPath expression.

Finally = ->xpath() will return a list of matching nodes, so as this should be the only one (making an assumption here) then it uses [0] in some of the echo's.

This also outputs...

array(1) {
  [0] =>
  class SimpleXMLElement#5 (0) {
  }
}
/home/image.jpg
<wp:meta_value><![CDATA[/home/image.jpg]]></wp:meta_value>

Upvotes: 1

Related Questions