这个值
//myfile.txt
data:[
{'name': 'Item 1', 'icon': 'snowplow', 'inv': 'B123', 'eh': 'h'},
{'name': 'Item 2', 'icon': 'snowplow', 'inv': 'B456', 'eh': 'h'},
{'name': 'Item 3', 'icon': 'snowplow', 'inv': 'B789', 'eh': 'h'},
{'name': 'Item 4', 'icon': 'snowplow', 'inv': 'B102', 'eh': 'h'}
]存储在一个我无法更改的*.txt文件中。如果我像这样用PHP读取这个文本文件:
$fn = fopen("myfile.txt","r");
while(! feof($fn)) {
$result = fgets($fn);
// echo $result[name];
// echo $result[icon];
// echo $result[inv];
// echo $result[eh];
}
fclose($fn);如何用PHP循环这些值?
发布于 2021-12-17 12:06:57
正如所指出的,如果源数据被正确地格式化为已知的数据类型,比如JSON,甚至XML,那么这个任务就会简单得多,也不会那么容易失败。要伪造上面的数据,以便更容易解析,您需要删除data:并更改双引号的单引号,然后再像通常那样继续。值得注意的是,这是一件有点烦人的事.
/*
replace the single quotes for double quotes
then split the resulting string using `data:` as the delimiter
and then convert to JSON
*/
list( $junk, $data )=explode( 'data:', str_replace( "'", '"', file_get_contents('myfile.txt') ) );
$json=json_decode( $data );
foreach( $json as $obj ){
/*
to get an unknown, potentially large, number of items from each object within data structure
you can iterate through the keys of the sub-object like this.
*/
$keys=array_keys( get_object_vars( $obj ) );
$tmp='';
foreach( $keys as $key )$tmp.=sprintf( '%s=%s, ', $key, $obj->$key );
printf('<div>%s</div>', $tmp );
/* Or, with known items like this: */
echo $obj->name . ' ' . $obj->icon . '/* etc */<br />';
}https://stackoverflow.com/questions/70392500
复制相似问题