Sochin
Sochin

Reputation: 23

XPath and PHP troubleshooting

I get this error:

Notice: Trying to get property of non-object in

Applies to: echo $result->Data;

And this output:

Array ()

Background Informations

A function returns a string which contains an XML file.

I want to get some data from two tags and deal with them on their own.

String Data

$data="
<SyncML xmlns='SYNCML:SYNCML1.0'> 
<SyncHdr> 
</SyncHdr> 
<SyncBody> 
   <betameta>
         WANT 1
   </betameta> 
   <Add> 
      <Data>
         WANT 2
      </Data>
   </Add> 
</SyncBody> 
</SyncML>";

In the above data, I want values "WANT 1" and "WANT 2"

Code so far

$xml = simplexml_load_string($data);
$result = $xml->xpath("/SyncML/SyncBody");
print_r($result);
echo $result->Data;

Upvotes: 0

Views: 252

Answers (3)

Wrikken
Wrikken

Reputation: 70460

$xml->registerXPathNamespace('default','SYNCML:SYNCML1.0');
$result = $xml->xpath("/default:SyncML/default:SyncBody");

Upvotes: 2

Martin
Martin

Reputation: 235

The only solution I can find is the following:

<?php

$data= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<SyncML> 
<SyncHdr> 
</SyncHdr> 
<SyncBody> 
   <betameta>
         WANT 1
   </betameta> 
   <Add> 
      <Data>
         WANT 2
      </Data>
   </Add> 
</SyncBody> 
</SyncML>
XML;

$xml = simplexml_load_string($data);
$result = $xml->xpath("/SyncML/SyncBody");
print_r($result);
echo $result;

is there anyway you can loose the xmlns?

This will output:

Array
(
    [0] => SimpleXMLElement Object
        (
            [betameta] => 
         WANT 1

            [Add] => SimpleXMLElement Object
                (
                    [Data] => 
         WANT 2

                )

        )

)

Upvotes: -1

k_b
k_b

Reputation: 2480

Remove the trailing slash.

Upvotes: 0

Related Questions