It seemed like a simple thing, but it took hours and heartbroken. In the file below, find a url with id=6. The file name is my.xml.
<?xml version="1.0" encoding="UTF-8" ?>
<urlfile>
<urls>
<id>0</id>
<url>http://www.000.com</url>
</urls>
<urls>
<id>1</id>
<url>http://www.1111.com</url>
</urls>
<urls>
<id>4</id>
<url>http://www.44444.com</url>
</urls>
<urls>
<id>6</id>
<url>http://www.66666.com</url>
</urls>
</urlfile>
Do that in an action in a Zend Framework controller. The code snippet is as follows:
$file = file_get_contents('my.xml');
$xml = simplexml_load_string($file);
$result = $xml->xpath('/urlfile/urls');
require_once('Zend/Debug.php');
Zend_Debug::Dump($result);
As a result, at the level of the urls node, it becomes a normal array. The next layer is still the SimpleXMLElement object. The data from the dump is as follows:
array(4) { [0] => object(SimpleXMLElement)#41 (2) { ["id"] => string(1) "0" ["url"] => string(18) "http://www.000.com" } [1] => object(SimpleXMLElement)#42 (2) { ["id"] => string(1) "1" ["url"] => string(41) "http://www.1111.com" } [2] => object(SimpleXMLElement)#43 (2) { ["id"] => string(1) "4" ["url"] => string(33) "http://www.4444.com" } [3] => object(SimpleXMLElement)#44 (2) { ["id"] => string(1) "6" ["url"] => string(33) "http://www.6666.com" } }
Is there a difference? have! If it is a normal array, you will definitely find the corresponding url when id=6.
foreach ($result as $k => $list )
{
if($list['id'] == $id )
{
$row['url'] = $list['url'];
//$row是我要送到页的一个数组,里面还有其它很多数据
}
}
As a result you found,
$row['url'] = null
The correct way is:
foreach ($result as $k => $list )
{
if($list->id == $id )
{
$row['url'] = $list->url;
//$row是我要送到页的一个数组,里面还有其它很多数据
}
}
is $list->id instead of $list['id']. is $list->url, not $list['url'].