Tom Tom - 5 months ago 22
PHP Question

Getting <g:id> value based on <link> in XML file with PHP

Here's the xml file:

<item>
<title>TITLE</title>
<link>
http://www.website.com/#!/1234
</link>
<g:id xmlns:g="http://base.google.com/ns/1.0">**this is what I need**</g:id>
<g:price xmlns:g="http://base.google.com/ns/1.0">100 USD</g:price>
<description>
description text
</description>
</item> <item>
<title>TITLE</title>
<link>
http://www.website.com/#!/0987
</link>
<g:id xmlns:g="http://base.google.com/ns/1.0">this is what I don't need</g:id>
<g:price xmlns:g="http://base.google.com/ns/1.0">100 USD</g:price>
<description>
description text
</description>
</item>


How do I get the value of g:id where link is http://www.website.com/#!/1234

Thank you!

This is the code I use to fatch:

$xml = new SimpleXMLElement($link);
foreach ($xml as $value){
if($value['link']=="http://www.website.com/#!/1234"){
echo $value['g:id'];
}
}

Answer

Next code searches for the value of g:id where link is "http://www.website.com/#!/1234" (when the value is found it is displayed) :

<?php
$data = <<<BLOCK
<item>
<title>TITLE</title>
<link>
http://www.website.com/#!/1234
</link>
<g:id xmlns:g="http://base.google.com/ns/1.0">**this is what I need**</g:id>
<g:price xmlns:g="http://base.google.com/ns/1.0">100 USD</g:price>
<description>
description text
</description>
<item>    </item>
<title>TITLE</title>
<link>
http://www.website.com/#!/0987
</link>
<g:id xmlns:g="http://base.google.com/ns/1.0">this is what I don't need</g:id>
<g:price xmlns:g="http://base.google.com/ns/1.0">100 USD</g:price>
<description>
description text
</description>
</item>
BLOCK;

$parser = xml_parser_create();
xml_parse_into_struct( $parser, $data, $vals, $index );
xml_parser_free( $parser );
$next = false; // THIS VARIABLE IS VERY IMPORTANT. THE FOREACH VISITS EACH
               // TAG, ONE BY ONE, SO, WHEN THE "LINK" TAG IS READ, IT'S
               // NECESSARY TO WAIT FOR THE NEXT LOOP OF THE FOREACH. WHEN
               // $NEXT==TRUE, MEANS THAT "http://www.website.com/#!/1234"
               // WAS FOUND, SO THE TAG "G:ID" IS THE ONE WE ARE LOOKING FOR.
foreach ( $vals as $item ) // VISIT EACH TAG IN XML DATA (TITLE,LINK,G:ID,...)
{ // CHECK IF CURRENT TAG'S VALUE IS "http://www.website.com/#!/1234".
  // STR_REPLACE IS USED BECAUSE "LINK" TAG TAKES THREE LINES AND ITS VALUE
  // CONTAINS LINE BREAKS.
  if ( strcasecmp( str_replace( array("\r","\n"),'',$item[ "value" ] ),
                   "http://www.website.com/#!/1234" ) == 0 )
     $next = true;
  if ( $next &&
       ( strcasecmp( $item[ "tag" ],"g:id" ) == 0 ) )
     { echo $item[ "value" ];
       break;
     }
}
?>

Just corrected an error in the XML data : the tag </item> <item> is wrong and confuses the XML parser, so I replaced it by <item> </item> (in the middle of the XML data in your question).

With previous change, if the value "http://www.website.com/#!/0987" is searched, it will display "this is what I don't need".