Jump to content

Extract simple values from XML


Stal

Recommended Posts

Hi, I am looking for a solution to this problem I am faced with.

 

I have a website which i can query and it replies with a small amount of xml data with regards to a particular product, eg spec, weight, stock etc.  I am trying to create a small script that will query that page and extract the values of the xml response, eg the xml data may look like this:

 

<?xml version="1.0" ?> 
- <product>
  <result>OK</result> 
    <description>SOME PRODUCT</description> 
  <extendeddescription>TECHNICAL SPEC</extendeddescription> 
  <weight>9.35</weight> 
  <stock>434</stock> 
  </product>

 

I need to capture this response and extract the values of description, stock, etc as variables i can use in PHP.  Then i can call this page for each product code required, eg www.mydomain.com/script.php?product_code=12345

 

Can anyone point me in the right direction as i am struggling to find any info as to how to extract the values i need.

 

??? ??? ???

 

Thanks  ;D

Link to comment
https://forums.phpfreaks.com/topic/38330-extract-simple-values-from-xml/
Share on other sites

ok, how about another possibility.

 

Is there a PHP function i can use to extract everything between 2 values, eg:

 

$description = strip everything bewteen "<description>" and "</description>" from $xml_result;
$weight = strip everything bewteen "<weight>" and "</weight>" from $xml_result;

etc....

 

???

I would use the SimpleXML object. Its dead simple to use like this:

Check out the php manual for detailed info.

 

DomXML is soooooooooo php4 :P

 

<?
$xml = <<<XML
<?xml version="1.0" ?> 
<products>
  <product>
    <result>OK</result> 
    <description>Product 1</description> 
    <extendeddescription>TECHNICAL SPEC</extendeddescription> 
    <weight>9.35</weight> 
    <stock>434</stock> 
  </product>
  
  <product>
    <result>OK</result> 
    <description>Product 2</description> 
    <extendeddescription>TECHNICAL SPEC</extendeddescription> 
    <weight>5.35</weight> 
    <stock>132</stock> 
  </product>
</products>
XML;

$xmlobj = simplexml_load_string($xml);

foreach ($xmlobj as $product) {   
  print (
    $product -> result."<br />".
    $product -> description."<br />".
    $product -> extendeddescription."<br />".
    $product -> weight."<br />".
    $product -> stock."<br /><br />"
  );
}
?>

Before php5 came along I used a XMLParser class (by Marcus Pont) that I found on PHPClasses site. The data array produced by the class was remarkably similar to the ones produced by php5 function.

 

Im attaching the code if you're interested.

 

[attachment deleted by admin]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.