Will
Will

Reputation: 295

Parsing XML-Like Web Service (web service returns xml within a string)

I'm trying to parse a "not-so-normal" XML web service. It appears the web service is returning a string, with XML inside that string.

The XML looks like this:

<string>
  <NewDataSet>
    <Table>
      <CATID>0</CATID>
      <DEPID>0</DEPID>
    </Table>
    <Table>
      <CATID>1</CATID>
      <DEPID>1</DEPID>
    </Table>
  </NewDataSet>
<string>

This is my code as of right now, I've already tried numerous variations but can't get anything to work. Most of the time it just returns nothing. I've echoed $xml and it will return all the XML, but I just need to show the CATID and nothing else.

<?php

$file = file_get_contents('http://theWebSericeLink.here');
$xml = simplexml_load_string($file);

 //echo $xml;
 foreach($xml->Table as $item) {
   echo $item->CATID;
 }
?>

I've also tried:

   foreach($xml->NewDataSet->Table as $item)

and

   foreach($xml->String->NewDataSet->Table as $item)

Thanks in advance.

Upvotes: 0

Views: 3839

Answers (4)

Will
Will

Reputation: 295

I figured it out.

Before my foreach function, I created an xml file from the "xml string" the web service was returning:

$xml = simplexml_load_string($file);
$feed = '<?xml version="1.0" encoding="ISO-8859-1"?>'.$xml;

file_put_contents("workhorse.xml", $feed);
$myxml=simplexml_load_file("workhorse.xml");

Upvotes: 0

Thomas Gensou
Thomas Gensou

Reputation: 76

As a first step, close the tag at the end, and start with "print_r" the xml variable.

print_r($xml);

As there are parents and children tags, It is like an array to get a result through each field.

In your case,

<string>
   <NewDataSet>
     <Table>

So

$tables = $xml->NewDataSet->Table;

foreach ($tables as $table)
{
    foreach ($table->CATID as $catid){
        echo $catid, "\n";
    }
}

Upvotes: 0

Padmanathan J
Padmanathan J

Reputation: 4620

Try this

<?php
$k = '<string>
    <NewDataSet>
        <Table>
          <CATID>0</CATID>
          <DEPID>0</DEPID>
        </Table>
        <Table>
          <CATID>1</CATID>
          <DEPID>0</DEPID>
        </Table>
    </NewDataSet>
</string>';
$xml = simplexml_load_string($k);

   foreach($xml->NewDataSet->Table as $read){       
     echo $read->CATID."<br>";
    }
?>

Output

0
1

Upvotes: 1

Jim
Jim

Reputation: 1315

If you can see the XML when you echo it, then you may need to use xpath.

$id = $xml->xpath('/table/CATID'); 

Upvotes: 0

Related Questions